package com.emm.yixun.customer.service.impl.app;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jws.WebService;

import com.emm.yixun.basic.mapper.*;
import com.emm.yixun.common.app.*;
import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import net.sf.ehcache.CacheManager;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.AreaService;
import com.emm.yixun.basic.service.AuditService;
import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.BusinessRelationService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DepartmentService;
import com.emm.yixun.basic.service.DialTransactionalService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.DistributionService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.FollowService;
import com.emm.yixun.basic.service.HaveReceiveRefundService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.MerchantResourcesService;
import com.emm.yixun.basic.service.MerchantService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NeedReceiveRefundService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PermissionService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectImgService;
import com.emm.yixun.basic.service.ProjectInfoService;
import com.emm.yixun.basic.service.ProjectQuestionnaireService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.RoleService;
import com.emm.yixun.basic.service.SignedPayService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.AddCustomerReqDto;
import com.emm.yixun.common.app.AddCustomerResDto;
import com.emm.yixun.common.app.AddFollowReqDto;
import com.emm.yixun.common.app.AddFollowResDto;
import com.emm.yixun.common.app.AddPayDepositReqDto;
import com.emm.yixun.common.app.AddPayDepositResDto;
import com.emm.yixun.common.app.AddSignedReqDto;
import com.emm.yixun.common.app.AddSignedResDto;
import com.emm.yixun.common.app.AddSubscribeReqDto;
import com.emm.yixun.common.app.AddSubscribeResDto;
import com.emm.yixun.common.app.BusinessAuditReqDto;
import com.emm.yixun.common.app.BusinessAuditResDto;
import com.emm.yixun.common.app.CheckCustomerPhoneReqDto;
import com.emm.yixun.common.app.CheckCustomerPhoneResDto;
import com.emm.yixun.common.app.DistributionConsultantReqDto;
import com.emm.yixun.common.app.DistributionConsultantResDto;
import com.emm.yixun.common.app.EditCustomerReqDto;
import com.emm.yixun.common.app.EditCustomerResDto;
import com.emm.yixun.common.app.EditFollowReqDto;
import com.emm.yixun.common.app.EditFollowResDto;
import com.emm.yixun.common.app.EditPayDepositReqDto;
import com.emm.yixun.common.app.EditPayDepositResDto;
import com.emm.yixun.common.app.EditSignedReqDto;
import com.emm.yixun.common.app.EditSignedResDto;
import com.emm.yixun.common.app.EditSubscribeReqDto;
import com.emm.yixun.common.app.EditSubscribeResDto;
import com.emm.yixun.common.app.GetAuditListReqDto;
import com.emm.yixun.common.app.GetAuditListResDto;
import com.emm.yixun.common.app.GetCallBackReqDto;
import com.emm.yixun.common.app.GetCallBackResDto;
import com.emm.yixun.common.app.GetConsultantListReqDto;
import com.emm.yixun.common.app.GetConsultantListResDto;
import com.emm.yixun.common.app.GetCustomerAnalysisListReqDto;
import com.emm.yixun.common.app.GetCustomerAnalysisListResDto;
import com.emm.yixun.common.app.GetCustomerDetailReqDto;
import com.emm.yixun.common.app.GetCustomerDetailResDto;
import com.emm.yixun.common.app.GetCustomerListReqDto;
import com.emm.yixun.common.app.GetCustomerListResDto;
import com.emm.yixun.common.app.GetCustomerVisitAnalysisListReqDto;
import com.emm.yixun.common.app.GetCustomerVisitAnalysisListResDto;
import com.emm.yixun.common.app.GetFollowListReqDto;
import com.emm.yixun.common.app.GetFollowListResDto;
import com.emm.yixun.common.app.GetGroupHeroListReqDto;
import com.emm.yixun.common.app.GetGroupHeroListResDto;
import com.emm.yixun.common.app.GetHeroListReqDto;
import com.emm.yixun.common.app.GetHeroListResDto;
import com.emm.yixun.common.app.GetMemberScoreListReqDto;
import com.emm.yixun.common.app.GetMemberScoreListResDto;
import com.emm.yixun.common.app.GetNextReminderListReqDto;
import com.emm.yixun.common.app.GetNextReminderListResDto;
import com.emm.yixun.common.app.GetPayDepositDetailReqDto;
import com.emm.yixun.common.app.GetPayDepositDetailResDto;
import com.emm.yixun.common.app.GetPayDepositListReqDto;
import com.emm.yixun.common.app.GetPayDepositListResDto;
import com.emm.yixun.common.app.GetProjectBusinessListReqDto;
import com.emm.yixun.common.app.GetProjectBusinessListResDto;
import com.emm.yixun.common.app.GetRecommendCustomerListReqDto;
import com.emm.yixun.common.app.GetRecommendCustomerListResDto;
import com.emm.yixun.common.app.GetSearchListReqDto;
import com.emm.yixun.common.app.GetSearchListResDto;
import com.emm.yixun.common.app.GetSignedDetailReqDto;
import com.emm.yixun.common.app.GetSignedDetailResDto;
import com.emm.yixun.common.app.GetSignedHaveAmountReqDto;
import com.emm.yixun.common.app.GetSignedHaveAmountResDto;
import com.emm.yixun.common.app.GetSignedListReqDto;
import com.emm.yixun.common.app.GetSignedListResDto;
import com.emm.yixun.common.app.GetSubscribeDetailReqDto;
import com.emm.yixun.common.app.GetSubscribeDetailResDto;
import com.emm.yixun.common.app.GetSubscribeListReqDto;
import com.emm.yixun.common.app.GetSubscribeListResDto;
import com.emm.yixun.common.app.GetUserCallListReqDto;
import com.emm.yixun.common.app.GetUserCallListResDto;
import com.emm.yixun.common.app.GetWorkloadStatisticsListReqDto;
import com.emm.yixun.common.app.GetWorkloadStatisticsListResDto;
import com.emm.yixun.common.app.MCCusUniqueReqDto;
import com.emm.yixun.common.app.MCCusUniqueResDto;
import com.emm.yixun.common.app.MCQueryProjectReqDto;
import com.emm.yixun.common.app.MCQueryProjectResDto;
import com.emm.yixun.common.app.QueryAgentInfoReqDto;
import com.emm.yixun.common.app.QueryAgentInfoResDto;
import com.emm.yixun.common.app.QueryCustomerFollowInfoReqDto;
import com.emm.yixun.common.app.QueryCustomerFollowInfoResDto;
import com.emm.yixun.common.app.QueryCustomerInfoReqDto;
import com.emm.yixun.common.app.QueryCustomerInfoResDto;
import com.emm.yixun.common.app.QueryProjectInfoPomReqDto;
import com.emm.yixun.common.app.QueryProjectInfoPomResDto;
import com.emm.yixun.common.app.QueryProjectInfoReqDto;
import com.emm.yixun.common.app.QueryProjectInfoResDto;
import com.emm.yixun.common.app.QueryProjectQuestionnaireListReqDto;
import com.emm.yixun.common.app.QueryProjectQuestionnaireListResDto;
import com.emm.yixun.common.app.QueryProjectRelationAgentInfoReqDto;
import com.emm.yixun.common.app.QueryProjectRelationAgentInfoResDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.AgentInfoListRes;
import com.emm.yixun.common.app.servletentity.AnnexListRes;
import com.emm.yixun.common.app.servletentity.AppProjectQuestionnaire;
import com.emm.yixun.common.app.servletentity.AuditListRes;
import com.emm.yixun.common.app.servletentity.CirCumListRes;
import com.emm.yixun.common.app.servletentity.CusAnalysisListRes;
import com.emm.yixun.common.app.servletentity.CusVisitAnalysisListRes;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListReq;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListRes;
import com.emm.yixun.common.app.servletentity.CustomerFocusListRes;
import com.emm.yixun.common.app.servletentity.CustomerFollowInfoListRes;
import com.emm.yixun.common.app.servletentity.CustomerInfoListRes;
import com.emm.yixun.common.app.servletentity.DealCategoryListReq;
import com.emm.yixun.common.app.servletentity.FamilyMemberListReq;
import com.emm.yixun.common.app.servletentity.GroupHeroListRes;
import com.emm.yixun.common.app.servletentity.GroupHeroSignedListRes;
import com.emm.yixun.common.app.servletentity.GroupHeroSubListRes;
import com.emm.yixun.common.app.servletentity.HeroList;
import com.emm.yixun.common.app.servletentity.HistoryTaskInfoListRes;
import com.emm.yixun.common.app.servletentity.HomePageListRes;
import com.emm.yixun.common.app.servletentity.ImageListReq;
import com.emm.yixun.common.app.servletentity.ImageListRes;
import com.emm.yixun.common.app.servletentity.LiveActionListRes;
import com.emm.yixun.common.app.servletentity.MCProjectListRes;
import com.emm.yixun.common.app.servletentity.ModelListRes;
import com.emm.yixun.common.app.servletentity.NextReminderListRes;
import com.emm.yixun.common.app.servletentity.PaymentMethodListRes;
import com.emm.yixun.common.app.servletentity.ProjectInfoListRes;
import com.emm.yixun.common.app.servletentity.ProjectInfoPomListRes;
import com.emm.yixun.common.app.servletentity.SignedListRes;
import com.emm.yixun.common.app.servletentity.SignedPageRes;
import com.emm.yixun.common.app.servletentity.SubscribePageRes;
import com.emm.yixun.common.app.servletentity.SumPlanListRes;
import com.emm.yixun.common.app.servletentity.UserCallListRes;
import com.emm.yixun.common.app.servletentity.WorkloadStatisticsList;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.appDto.CustomerCountDto;
import com.emm.yixun.common.model.appDto.CustomerTopCount;
import com.emm.yixun.common.model.appDto.HeroCount;
import com.emm.yixun.common.model.appDto.MemberScoreCount;
import com.emm.yixun.common.model.appDto.WorkloadCount;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.FileUploadPorxyUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.config.DsfConfig;
import com.emm.yixun.customer.service.app.CustomerServiceAppFacade;
import com.emm.yixun.customer.service.impl.SendMessageService;
import com.emm.yixun.customer.service.impl.app.manage.AddCustomerManage;
import com.emm.yixun.customer.service.impl.app.manage.AddFollowManage;
import com.emm.yixun.customer.service.impl.app.manage.AddPayDepositManage;
import com.emm.yixun.customer.service.impl.app.manage.AddSubscribeManage;
import com.emm.yixun.customer.service.impl.app.manage.BusinessAuditManage;
import com.emm.yixun.customer.service.impl.app.manage.CusAppNoticeManage;
import com.emm.yixun.customer.service.impl.app.manage.DistributionConsultantManage;
import com.emm.yixun.customer.service.impl.app.manage.EditCustomerManage;
import com.emm.yixun.customer.service.impl.app.manage.EditPayDepositManage;
import com.emm.yixun.customer.service.impl.app.manage.EditSubscribeManage;
import com.emm.yixun.customer.service.impl.app.manage.GetConsultantListManage;
import com.emm.yixun.customer.service.impl.app.manage.GetCustomerDetailManage;
import com.emm.yixun.customer.service.impl.app.manage.GetCustomerListManage;
import com.emm.yixun.customer.service.impl.app.manage.GetFollowListManage;
import com.emm.yixun.customer.service.impl.app.manage.GetPayDepositDetailManage;
import com.emm.yixun.customer.service.impl.app.manage.GetPayDepositListManage;
import com.emm.yixun.customer.service.impl.app.manage.GetRecommendCustomerListManage;
import com.emm.yixun.customer.service.impl.app.manage.GetSearchListManage;
import com.emm.yixun.customer.service.impl.app.manage.GetSubscribeDetailManage;
import com.emm.yixun.customer.service.impl.app.manage.GetSubscribeListManage;

@Service("customerServiceAppFacade")
@WebService(endpointInterface = "com.emm.yixun.customer.service.app.CustomerServiceAppFacade")
public class CustomerServiceAppFacadeImpl implements CustomerServiceAppFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CustomerService customerService;
	@Autowired
	private AddCustomerManage addCustomerManage;
	@Autowired
	private EditCustomerManage editCustomerManage;
	@Autowired
	private GetCustomerListManage getCustomerListManage;
	@Autowired
	private GetCustomerDetailManage getCustomerDetailManage;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private CacheManager cacheManager;
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private SignedService signedService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private UserService userService;
	@Autowired
	private AuditService auditService;
	@Autowired
	private AuditMapper auditMapper;
	@Autowired
	private SignedPayService signedPayService;
	@Autowired
	private ImageService imageService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private GetSearchListManage getSearchListManage;
	@Autowired
	private AddFollowManage addFollowManage;
	@Autowired
	private GetFollowListManage getFollowListManage;
	@Autowired
	private GetConsultantListManage getConsultantListManage;
	@Autowired
	private GetRecommendCustomerListManage getRecommendCustomerListManage;
	@Autowired
	private DistributionConsultantManage distributionConsultantManage;
	@Autowired
	private GetPayDepositListManage getPayDepositListManage;
	@Autowired
	private AddPayDepositManage addPayDepositManage;
	@Autowired
	private EditPayDepositManage editPayDepositManage;
	@Autowired
	private GetPayDepositDetailManage getPayDepositDetailManage;
	@Autowired
	private GetSubscribeListManage getSubscribeListManage;
	@Autowired
	private GetSubscribeDetailManage getSubscribeDetailManage;
	@Autowired
	private AddSubscribeManage addSubscribeManage;
	@Autowired
	private EditSubscribeManage editSubscribeManage;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private BusinessAuditManage businessAuditManage;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private BusinessAbnormaService businessAbnormaService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessServiceImpl;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private TaskService taskService;
	 @Autowired
	 private RepositoryService repositoryService;
	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;
	@Autowired
	private MerchantResourcesService merchantResourcesService;
	@Autowired
	private FollowService followService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private DialTransactionalService dialTransactionalService;
	@Autowired
	private SendMessageService sendMessageService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private BaseCodeValueMapper baseCodeValueMapper;
	@Autowired
	private AreaService areaService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private SalesGroupUserMapper salesGroupUserMapper;
	@Autowired
	private ProjectInfoService projectInfoService;
	@Autowired
	private ProjectImgService projectImgService;
	@Autowired
	private BusinessRelationService businessRelationService;
	@Autowired
	private ProjectQuestionnaireService projectQuestionnaireService;
	@Autowired
	private BaseCodeValueService baseCodeValueService;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private ResourcesConfigMapper resourcesConfigMapper;

	@Value("${file.serviceUrl}")
	private String fileUploadUrl;

	SimpleDateFormat sdf_follow = new SimpleDateFormat("MM-dd");
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdf_all = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	DecimalFormat df = new DecimalFormat("#.00");
	DecimalFormat df_zero = new DecimalFormat("0.00");

	@Override
	public CheckCustomerPhoneResDto checkCustomerPhone(CheckCustomerPhoneReqDto reqDto) throws Exception {
		CheckCustomerPhoneResDto resDto = new CheckCustomerPhoneResDto();
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		// 验证客户联系手机号码是否重复
		CustomerDto cusDto = new CustomerDto();
		cusDto.setCustomerPhone(reqDto.getCustomerPhone());
		cusDto.setMerchantId(reqDto.getMerchantId());
		cusDto.setPeMobile(reqDto.getPeMobile());
		if("2".equals(reqDto.getOperType())){
			cusDto.setProjectCode(reqDto.getProjectCode());
		}
		List<Customer> cusEntity = customerMapper.selectCustomerPhoneByList(cusDto);
		if("1".equals(reqDto.getOperType())){
			//新增
			if (cusEntity.size() > 0) {
				for(int i=0;i<cusEntity.size();i++){
					if(cusEntity.get(i).getProjectCode().equals(reqDto.getProjectCode())){
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
						resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
					}
				}
			}
		}else if("2".equals(reqDto.getOperType())){
			//修改
			if (cusEntity.size() > 1) {
				resDto.setResult(ResultEnum.FAILURE.getNo());
				resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
				resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
			}else{
				//非当前会员,手机号重复
				for(Customer customer: cusEntity){
					String id = String.valueOf(customer.getId());
					if(!id.equals(reqDto.getCustomerId())){
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
						resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
					}
				}
			}
		}

		return resDto;
	}

	@Override
	@Transactional
	public AddCustomerResDto addCustomer(AddCustomerReqDto reqDto)
			throws Exception {
		AddCustomerResDto resDto = new AddCustomerResDto();
		CommonResDTO commonResDto = new CommonResDTO();

		//验证项目是否已删除
		Project project = projectService.selectById(reqDto.getProjectId());
		if(project == null){
			resDto.setResult(ResultEnum.FAILURE.getNo());
			resDto.setErrorCode(XFUNExceptionCode.USER_NOPROJECT.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_NOPROJECT.getDesin());
			return resDto;
		}

		// 验证客户联系手机号码、或个人信息手机号码是否重复
		CustomerDto cusDto = new CustomerDto();
		cusDto.setCustomerPhone(reqDto.getCustomerPhone());
		cusDto.setMerchantId(reqDto.getMerchantId());
		if(reqDto.getPeMobile() != null && !"".equals(reqDto.getPeMobile())){
			cusDto.setPeMobile(reqDto.getPeMobile());
		}
		List<Customer> cusEntity = customerMapper.selectCustomerPhoneByList(cusDto);
		if (cusEntity.size() > 0) {
			for(Customer cusr : cusEntity){
				if(cusr.getProjectId().equals(reqDto.getProjectId())){
					resDto.setResult(ResultEnum.FAILURE.getNo());
					resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
					resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
					return resDto;
				}
			}
		}

		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户

		// 4、记录客户信息 cus_tm_customer
		CustomerDto customerDto = addCustomerManage.addCustomer(reqDto);
		if (customerDto == null) {
			// 抛出异常
			throw new Exception("customer");
		}
		// 5、记录关注户型、意向房源、意向组团 cus_tr_business_relation
		// 关注户型
		List<String> houseTypeList = reqDto.getHouseTypeList();
		if (houseTypeList != null && houseTypeList.size() > 0) {
			commonResDto = addCustomerManage.addCusHouseTypeFocus(customerDto,
					houseTypeList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("houseType");
			}
		}

		// 关注组团(楼盘)
		List<String> premisesList = reqDto.getPremisesList();
		if (premisesList != null && premisesList.size() > 0) {
			commonResDto = addCustomerManage.addCusPremisesFocus(customerDto,
					premisesList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("premises");
			}
		}

		// 关注房号
		List<String> roomList = reqDto.getRoomList();
		if (roomList != null && roomList.size() > 0) {
			commonResDto = addCustomerManage.addCusRoomFocus(customerDto,
					roomList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("room");
			}
		}

		// 6、记录家庭成员 cus_tr_family_member
		// 家庭成员
		List<FamilyMemberListReq> familyMemberList = reqDto
				.getFamilyMemberList();
		if (familyMemberList != null && familyMemberList.size() > 0) {
			commonResDto = addCustomerManage.addCusFamily(customerDto,
					familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	@Transactional
	public AddCustomerIntentionResDto addCustomerIntention(AddCustomerIntentionReqDto reqDto)
			throws Exception {
		AddCustomerIntentionResDto resDto = new AddCustomerIntentionResDto();
		CommonResDTO commonResDto = new CommonResDTO();

		//验证项目是否已删除
		Project project = projectService.selectById(reqDto.getProjectId());
		if(project == null){
			resDto.setResult(ResultEnum.FAILURE.getNo());
			resDto.setErrorCode(XFUNExceptionCode.USER_NOPROJECT.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_NOPROJECT.getDesin());
			return resDto;
		}

		// 验证客户联系手机号码、或个人信息手机号码是否重复
		CustomerDto cusDto = new CustomerDto();
		cusDto.setCustomerPhone(reqDto.getCustomerPhone());
		cusDto.setMerchantId(reqDto.getMerchantId());
		if(reqDto.getPeMobile() != null && !"".equals(reqDto.getPeMobile())){
			cusDto.setPeMobile(reqDto.getPeMobile());
		}
		List<Customer> cusEntity = customerMapper.selectCustomerPhoneByList(cusDto);
		if (cusEntity.size() > 0) {
			for(Customer cusr : cusEntity){
				if(cusr.getProjectId().equals(reqDto.getProjectId())){
					resDto.setResult(ResultEnum.FAILURE.getNo());
					resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
					resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
					return resDto;
				}
			}
		}

		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户

		// 4、记录客户信息 cus_tm_customer
		CustomerDto customerDto = addCustomerManage.addCustomer(reqDto);
		if (customerDto == null) {
			// 抛出异常
			throw new Exception("customer");
		}
		// 5、记录关注户型、意向房源、意向组团 cus_tr_business_relation
		if (reqDto.getHouseTypeList() != null
				&& !"".equals(reqDto.getHouseTypeList())) {
			// 关注户型
			List<String> houseTypeList = reqDto.getHouseTypeList();
			commonResDto = addCustomerManage.addCusHouseTypeFocus(customerDto,
					houseTypeList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("houseType");
			}
		}

		// 关注组团(楼盘)
		if (reqDto.getPremisesList() != null
				&& !"".equals(reqDto.getPremisesList())) {
			List<String> premisesList = reqDto.getPremisesList();
			commonResDto = addCustomerManage.addCusPremisesFocus(customerDto,
					premisesList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("premises");
			}
		}

		// 关注房号
		if (reqDto.getRoomList() != null && !"".equals(reqDto.getRoomList())) {
			List<String> roomList = reqDto.getRoomList();
			commonResDto = addCustomerManage.addCusRoomFocus(customerDto,
					roomList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("room");
			}
		}

		// 6、记录家庭成员 cus_tr_family_member
		// 家庭成员
		if (!"".equals(reqDto.getFamilyMemberList())
				&& reqDto.getFamilyMemberList() != null) {
			List<FamilyMemberListReq> familyMemberList = reqDto
					.getFamilyMemberList();
			commonResDto = addCustomerManage.addCusFamily(customerDto,
					familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	@Transactional
	public EditCustomerResDto editCustomer(EditCustomerReqDto reqDto)
			throws Exception {
		EditCustomerResDto resDto = new EditCustomerResDto();
		CommonResDTO commonResDto = new CommonResDTO();

		// 查询出客户相关信息
		Customer customer = customerService.selectById(Long.parseLong(reqDto
				.getCustomerId()));

		//移动端针对渠道转客的客户，下属3个字段也不支持编辑{联系电话，货值途径，首次接触方式}
		if(StringUtils.isNotBlank(customer.getRecommendedChannelId())){
			reqDto.setCustomerPhone(customer.getCustomerPhone());
			reqDto.setFtContactWay(customer.getFtContactWay());
			reqDto.setInformedWay(customer.getInformedWay());
		}

		// 验证客户联系手机号码是否重复
		if (!customer.getCustomerPhone().equals(reqDto.getCustomerPhone())) {
			CustomerDto cusDto = new CustomerDto();
			cusDto.setCustomerPhone(reqDto.getCustomerPhone());
			cusDto.setMerchantId(reqDto.getMerchantId());
			if(reqDto.getPeMobile() != null && !"".equals(reqDto.getPeMobile())){
				cusDto.setPeMobile(reqDto.getPeMobile());
			}
			List<Customer> cusEntity = customerMapper.selectCustomerPhoneByList(cusDto);
			if (cusEntity.size() > 0) {
				for(Customer cusr : cusEntity){
					if(cusr.getProjectId().equals(reqDto.getProjectId())){
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
						resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
						return resDto;
					}
				}
			}
		}

		if (reqDto.getFamilyMemberList() != null
				&& !"".equals(reqDto.getFamilyMemberList())) {
			// 1、修改客户家庭成员(先删除再新增进行覆盖)
			List<FamilyMemberListReq> familyMemberList = reqDto
					.getFamilyMemberList();
			commonResDto = editCustomerManage.editCusFamily(customer,
					familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}else{
			//删除客户原有家庭成员,修改del_flag = 1
			FamilyMemberDto fmDto = new FamilyMemberDto();
			fmDto.setCustomerId(customer.getId());
			fmDto.setProjectCode(customer.getProjectCode());
			fmDto.setMemberType(MemberTypeEnum.CUSTOMER_ADD.getNo());
			fmDto.setBuyId(customer.getId());
			familyMemberService.destroy(fmDto);
		}

		if (reqDto.getRoomList() != null && !"".equals(reqDto.getRoomList())) {
			// 2、修改关注房号(先删除再新增进行覆盖)
			List<String> roomList = reqDto.getRoomList();
			commonResDto = editCustomerManage.editCusRoomFocus(customer,
					roomList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("room");
			}
		}else{
			QuerybusinessRelation(customer.getId(), customer.getProjectCode(), RelationTypeEnum.ROOM.getNo());
		}

		if (reqDto.getPremisesList() != null
				&& !"".equals(reqDto.getPremisesList())) {
			// 3、修改关注组团(楼盘)(先删除再新增进行覆盖)
			List<String> premisesList = reqDto.getPremisesList();
			commonResDto = editCustomerManage.editCusPremisesFocus(customer,
					premisesList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("premises");
			}
		}else{
			QuerybusinessRelation(customer.getId(), customer.getProjectCode(), RelationTypeEnum.PREMISES.getNo());
		}

		if (reqDto.getHouseTypeList() != null
				&& !"".equals(reqDto.getHouseTypeList())) {
			// 4、修改关注户型(先删除再新增进行覆盖)
			List<String> houseTypeList = reqDto.getHouseTypeList();
			commonResDto = editCustomerManage.editCusHouseTypeFocus(customer,
					houseTypeList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("houseType");
			}
		}else{
			QuerybusinessRelation(customer.getId(), customer.getProjectCode(), RelationTypeEnum.HOUSE_TYPE.getNo());
		}

		// 5、修改客户基本信息
		commonResDto = editCustomerManage.editCustomer(reqDto);

		customerServiceFacade.changeCustomerPerfect(customer.getId());

		if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
			// 抛出异常
			throw new Exception("customer");
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	@Transactional
	public EditCustomerIntentionResDto editCustomerIntention(EditCustomerIntentionReqDto  reqDto)
			throws Exception {
		EditCustomerIntentionResDto resDto = new EditCustomerIntentionResDto();
		CommonResDTO commonResDto = new CommonResDTO();

		// 查询出客户相关信息
		Customer customer = customerService.selectById(Long.parseLong(reqDto
				.getCustomerId()));

		// 验证客户联系手机号码是否重复
		if (!customer.getCustomerPhone().equals(reqDto.getCustomerPhone())) {
			CustomerDto cusDto = new CustomerDto();
			cusDto.setCustomerPhone(reqDto.getCustomerPhone());
			cusDto.setMerchantId(reqDto.getMerchantId());
			if(reqDto.getPeMobile() != null && !"".equals(reqDto.getPeMobile())){
				cusDto.setPeMobile(reqDto.getPeMobile());
			}
			List<Customer> cusEntity = customerMapper.selectCustomerPhoneByList(cusDto);
			if (cusEntity.size() > 0) {
				for(Customer cusr : cusEntity){
					if(cusr.getProjectId().equals(reqDto.getProjectId())){
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
						resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
						return resDto;
					}
				}
			}
		}

		if (reqDto.getFamilyMemberList() != null
				&& !"".equals(reqDto.getFamilyMemberList())) {
			// 1、修改客户家庭成员(先删除再新增进行覆盖)
			List<FamilyMemberListReq> familyMemberList = reqDto
					.getFamilyMemberList();
			commonResDto = editCustomerManage.editCusFamily(customer,
					familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}else{
			//删除客户原有家庭成员,修改del_flag = 1
			FamilyMemberDto fmDto = new FamilyMemberDto();
			fmDto.setCustomerId(customer.getId());
			fmDto.setProjectCode(customer.getProjectCode());
			fmDto.setMemberType(MemberTypeEnum.CUSTOMER_ADD.getNo());
			fmDto.setBuyId(customer.getId());
			familyMemberService.destroy(fmDto);
		}

		if (reqDto.getRoomList() != null && !"".equals(reqDto.getRoomList())) {
			// 2、修改关注房号(先删除再新增进行覆盖)
			List<String> roomList = reqDto.getRoomList();
			commonResDto = editCustomerManage.editCusRoomFocus(customer,
					roomList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("room");
			}
		}else{
			QuerybusinessRelation(customer.getId(), customer.getProjectCode(), RelationTypeEnum.ROOM.getNo());
		}

		if (reqDto.getPremisesList() != null
				&& !"".equals(reqDto.getPremisesList())) {
			// 3、修改关注组团(楼盘)(先删除再新增进行覆盖)
			List<String> premisesList = reqDto.getPremisesList();
			commonResDto = editCustomerManage.editCusPremisesFocus(customer,
					premisesList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("premises");
			}
		}else{
			QuerybusinessRelation(customer.getId(), customer.getProjectCode(), RelationTypeEnum.PREMISES.getNo());
		}

		if (reqDto.getHouseTypeList() != null
				&& !"".equals(reqDto.getHouseTypeList())) {
			// 4、修改关注户型(先删除再新增进行覆盖)
			List<String> houseTypeList = reqDto.getHouseTypeList();
			commonResDto = editCustomerManage.editCusHouseTypeFocus(customer,
					houseTypeList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("houseType");
			}
		}else{
			QuerybusinessRelation(customer.getId(), customer.getProjectCode(), RelationTypeEnum.HOUSE_TYPE.getNo());
		}

		// 5、修改客户基本信息(含意向等级判断)
		if("1".equals(customer.getIsIntentionIntact()) && "0".equals(reqDto.getIsIntentionIntact())){
			reqDto.setFillInfoTime(Calendar.getInstance().getTime());
		}
		if(reqDto.getProjectId() == null) {
			reqDto.setProjectId(customer.getProjectId());
		}
		commonResDto = editCustomerManage.editCustomer(reqDto);
		if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
			// 抛出异常
			throw new Exception("customer");
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	public CheckCustomerIntentionResDto checkCustomerIntention(CheckCustomerIntentionReqDto reqDto){
		CheckCustomerIntentionResDto resDto = new CheckCustomerIntentionResDto();
		boolean result = false;
		if(reqDto.getCheckWay() == 0){//默认验证客户端传的信息
			result = checkIntentionLevel(reqDto);
		}else if(reqDto.getCheckWay() == 1){//验证数据库信息【认购，签约】
			//查询数据库信息
			result = checkIsA(reqDto.getId());
		}

		if(result){
			resDto.setResult("1");
			resDto.setIntentionResult("1");//意向等级满足
		}else{
			resDto.setResult("1");
			resDto.setIntentionResult("0");//意向等级不满足
		}
		return resDto;
	}


	public void QuerybusinessRelation(Long customerId, String projectCode, String relationType){
		BusinessRelationDto brDto = new BusinessRelationDto();
		brDto.setSingleId(customerId);
		brDto.setProjectCode(projectCode);
		brDto.setRelationType(relationType);
		List<BusinessRelation> businessRelationList = businessRelationService.selectListByDto(brDto);
		if(businessRelationList.size() > 0){
			for(BusinessRelation businessRelation : businessRelationList){
				BusinessRelationDto brDto_entity = new BusinessRelationDto();
				brDto_entity.setId(businessRelation.getId());
				businessRelationService.destroy(brDto_entity);
			}
		}
	}

	@Override
	public GetCustomerDetailResDto getCustomerDetail(
			GetCustomerDetailReqDto reqDto) {
		// 1、查询家庭成员
		// 2、查询关注房号
		// 3、查询意向组团
		// 4、查询意向户型
		// 5、客户基本信息
		return getCustomerDetailManage.getCustomerDetail(reqDto);
	}

	@Override
	public GetCustomerListResDto getCustomerList(GetCustomerListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、查询客户列表
		return getCustomerListManage.getCustomerList(reqDto);

	}
	@Override
	public GetCustomerListResDto getCustomerListLC(GetCustomerListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、查询客户列表
		return getCustomerListManage.getCustomerListLC(reqDto);

	}



	@Override
	public GetSearchListResDto getSearchList(GetSearchListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、查询客户
		return getSearchListManage.getSearchList(reqDto);
	}

	@Override
	public AddFollowResDto addFollow(AddFollowReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、新增跟进
		return addFollowManage.addFollow(reqDto);
	}

	@Override
	public GetFollowListResDto getFollowList(GetFollowListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、查询跟进
		return getFollowListManage.getFollowList(reqDto);
	}

	@Override
	public GetConsultantListResDto getConsultantList(
			GetConsultantListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、查询职业顾问
		return getConsultantListManage.getConsultantList(reqDto);
	}

	@Override
	public DistributionConsultantResDto distributionConsultant(
			DistributionConsultantReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、分配职业顾问
		return distributionConsultantManage.distributionConsultant(reqDto);
	}

	@Override
	public GetPayDepositListResDto getPayDepositList(
			GetPayDepositListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、认筹列表
		return getPayDepositListManage.getPayDepositList(reqDto);
	}

	@Override
	public AddPayDepositResDto addPayDeposit(AddPayDepositReqDto reqDto)
			throws Exception {
		AddPayDepositResDto resDto = new AddPayDepositResDto();
		CommonResDTO commonResDto = new CommonResDTO();
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、新增认筹
		// 4.1、判断是否可认筹,房源为:可售、认筹状态下可认筹
		commonResDto = addPayDepositManage.check(reqDto);
		if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
			resDto.setErrorCode(commonResDto.getErrorCode());
			resDto.setErrorMsg(commonResDto.getErrorMsg());
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		ProjectDto projectDto = new ProjectDto();
		projectDto.setMerchantId(reqDto.getMerchantId());
		projectDto.setProjectCode(reqDto.getProjectCode());

		Project project = projectService.selectByDto(projectDto);
		if (null == project) {
			resDto.setErrorCode("99998");
			resDto.setErrorMsg("项目不存在");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		reqDto.setProjectId(project.getId());
		User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
		if (null == user) {
			resDto.setErrorCode("99998");
			resDto.setErrorMsg("用户不存在");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		reqDto.setUserCode(user.getUserCode());

		//校验认筹号是否重复
		if(reqDto.getPayDepositCode() != null && !"".equals(reqDto.getPayDepositCode())){
			PayDepositDto pd_dto = new PayDepositDto();
			pd_dto.setMerchantId(reqDto.getMerchantId());
			pd_dto.setProjectCode(reqDto.getProjectCode());
			pd_dto.setDepositCode(reqDto.getPayDepositCode());
			List<PayDeposit> payDeposit_list =  payDepositService.selectListByDto(pd_dto);
			if(payDeposit_list.size() > 0){
				resDto.setErrorCode("99998");
				resDto.setErrorMsg("已经存在该认筹号!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		}
		if(reqDto.getIsPayDeposit().equals(IsPaydepositEnum.NO.getNo())){
			//有房认筹,查询客户是否认筹过此房源
			//过滤未删除、审核中、审核已通过的认筹记录
	        PayDepositDto pdDto = new PayDepositDto();
	        pdDto.setCustomerId(Long.parseLong(reqDto.getCustomerId()));
	        pdDto.setRoomId(Long.parseLong(reqDto.getRoomId()));
	        pdDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
	        //审核中的认筹
	        pdDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			List<PayDeposit> pdAuditList = payDepositService.selectListByDto(pdDto);
			int auditSize = 0;
			if(null != pdAuditList){
				auditSize = pdAuditList.size();
			}

			//已通过的认筹
			pdDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			List<PayDeposit> pdSuccessList = payDepositService.selectListByDto(pdDto);
			int successSize = 0;
			if(null != pdSuccessList){
				successSize = pdSuccessList.size();
			}
			if((auditSize + successSize) > 0){
				//抛出异常
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("客户已认筹此房源，不能再次发起认筹!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		}

		//动态获取认筹流程KEY
		String startProcessKey = activitiProcessService.getProcessKey(reqDto.getMerchantId(), project.getId(), ProcessTypeEnums.PROCESS_KEY_3);
		if(StringUtils.isEmpty(startProcessKey)){
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("项目未设置认筹流程，请去项目流程菜单配置!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		// 检查流程节点是否已设置人员
		String processKey = startProcessKey;
		boolean isSeting = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), project.getId(), processKey);
		if (!isSeting) {
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("认筹审批流程节点人员未设置!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		// 4.2、新增认筹
		PayDepositDto payDepositDto = addPayDepositManage.addPayDeposit(reqDto);
		if (payDepositDto == null) {
			// 抛出异常
			throw new Exception("payDeposit");
		}
		// 4.3、新增认筹家庭成员
		List<CustomerFamilyListReq> cusFmReqList = reqDto
				.getCustomerFamilyList();
		commonResDto = addPayDepositManage.addPayDepositFamily(payDepositDto,
				cusFmReqList);
		if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
			// 抛出异常
			throw new Exception("family");
		}

		// 4.4、发送消息
		/**
		 * 1.提交认筹审核,修改状态为审核中,保存流程ID 2.修改房源状态认筹
		 */
		String pid = null;
		if ("1".equals(reqDto.getAuditStatus())) {
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(user.getUserAccount());
			pid=activitiProcessService.startProcessInstance(user.getMerchantId(),project.getId(), startProcessKey, payDepositDto.getId().toString(), variables);
			PayDepositDto updateDto = new PayDepositDto();
			updateDto.setId(payDepositDto.getId());
			updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			updateDto.setProcInstId(pid);
			payDepositService.update(updateDto);

			// 修改房源状态为认筹
			ProjectRoomDto projectRoomDto = new ProjectRoomDto();
			projectRoomDto.setId(payDepositDto.getRoomId());
			projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());
			projectRoomService.update(projectRoomDto);
		}

		// 4.5、添加消息（提交审核时，推送push审核消息）
		if ("1".equals(reqDto.getAuditStatus())) {
			if(pid != null){
				payDepositDto.setProcInstId(pid);
			}
		}

		// 4.6、新增合同附件【图片】
		if (reqDto.getImageList() != null) {
			List<ImageListReq> imageList = reqDto.getImageList();
			commonResDto = addPayDepositManage.addPayDepositImage(payDepositDto, imageList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("image");
			}
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public EditPayDepositResDto editPayDeposit(EditPayDepositReqDto reqDto)
			throws Exception {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、修改认筹
		EditPayDepositResDto resDto = new EditPayDepositResDto();
		//动态获取认筹流程KEY
		String startProcessKey = activitiProcessService.getProcessKey(reqDto.getMerchantId(), reqDto.getProjectId(), ProcessTypeEnums.PROCESS_KEY_3);
		if(StringUtils.isEmpty(startProcessKey)){
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("项目未设置认筹流程，请去项目流程菜单配置!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		// 检查流程节点是否已设置人员
		String processKey = startProcessKey;
		boolean isSeting = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), reqDto.getProjectId(), processKey);
		if (!isSeting) {
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("认筹审批流程节点人员未设置!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		resDto = editPayDepositManage.editPayDeposit(reqDto);
		if (StringUtils.isNotEmpty(resDto.getErrorCode())) {
			// 抛出异常
			return resDto;
			//throw new Exception("payDeposit");
		}

		/**
		 * 1.提交认筹审核,修改状态为审核中,保存流程ID 2.修改房源状态认筹
		 */
		String pid = null;
		PayDeposit payDeposit = null;
		if ("1".equals(reqDto.getAuditStatus())) {
			payDeposit = payDepositService.selectById(Long
					.parseLong(reqDto.getPayDepositId()));
			if (payDeposit == null) {
				resDto.setErrorCode("00001");
				resDto.setErrorMsg("认筹记录不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			User user = userService
					.selectById(Long.valueOf(reqDto.getUserId()));
			if (null == user) {
				resDto.setErrorCode("99998");
				resDto.setErrorMsg("用户不存在");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(user.getUserAccount());
			pid=activitiProcessService.startProcessInstance(user.getMerchantId(), payDeposit.getProjectId(), startProcessKey, payDeposit.getId().toString(), variables);
			PayDepositDto updateDto = new PayDepositDto();
			updateDto.setId(payDeposit.getId());
			updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			updateDto.setProcInstId(pid);
			payDepositService.update(updateDto);

			// 修改房源状态为认筹
			ProjectRoomDto projectRoomDto = new ProjectRoomDto();
			projectRoomDto.setId(payDeposit.getRoomId());
			projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());
			projectRoomService.update(projectRoomDto);
		}

		//添加消息（提交审核时，推送push审核消息）
		if ("1".equals(reqDto.getAuditStatus())) {
			if(pid != null){
				payDeposit.setProcInstId(pid);
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public GetPayDepositDetailResDto getPayDepositDetail(
			GetPayDepositDetailReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、认筹详情
		return getPayDepositDetailManage.getPayDepositDetail(reqDto);
	}

	@Override
	public GetSubscribeListResDto getSubscribeList(GetSubscribeListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、认购列表
		return getSubscribeListManage.getSubscribeList(reqDto);
	}

	/**
	 * 新增认购（addSubscribe）
	 */
	@SuppressWarnings("unused")
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public AddSubscribeResDto addSubscribe(AddSubscribeReqDto reqDto)
			throws Exception {
		AddSubscribeResDto resDto = new AddSubscribeResDto();
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、认购详情
		// 4.1、判断是否可认购,房源为:可售、认筹状态下可认购
		// 房源保留: 认购需判断保留客户是否与认购客户一致.暂不处理,二期再做
		CommonResDTO commonResDto = addSubscribeManage.check(reqDto);
		if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
			resDto.setErrorCode(commonResDto.getErrorCode());
			resDto.setErrorMsg(commonResDto.getErrorMsg());
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		//校验认购号是否重复
		if(reqDto.getSubscribeCode() != null && !"".equals(reqDto.getSubscribeCode())){
			SubscribeDto sb_dto = new SubscribeDto();
			sb_dto.setMerchantId(reqDto.getMerchantId());
			sb_dto.setProjectCode(reqDto.getProjectCode());
			sb_dto.setSubscribeCode(reqDto.getSubscribeCode());
			List<Subscribe> subscribeList =  subscribeService.selectListByDto(sb_dto);
			if(subscribeList.size() > 0){
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("已经存在该认购号!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		}

		String startProcessKey_rgzk = null;
		String startProcessKey_rg = null;
		if (reqDto.getDiscountApproval().equals("1") && reqDto.getDiscountApproval() != null){
			//动态获取认购折扣流程KEY
			startProcessKey_rgzk = activitiProcessService.getProcessKey(reqDto.getMerchantId(), reqDto.getProjectId(), ProcessTypeEnums.PROCESS_KEY_17);
			if(StringUtils.isEmpty(startProcessKey_rgzk)){
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("项目未设置认购折扣流程，请去项目流程菜单配置!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			// 检查流程节点是否已设置人员（认购折扣审批）
			String processKey_diszk = startProcessKey_rgzk;
			boolean isSeting_diszk = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), reqDto.getProjectId(), processKey_diszk);
			if (!isSeting_diszk) {
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("认购折扣审批流程节点人员未设置!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		}

		if(reqDto.getDiscountApproval().equals("0") && reqDto.getDiscountApproval() != null){
			//动态获取认购流程KEY
			startProcessKey_rg = activitiProcessService.getProcessKey(reqDto.getMerchantId(), reqDto.getProjectId(), ProcessTypeEnums.PROCESS_KEY_5);
			if(StringUtils.isEmpty(startProcessKey_rg)){
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("项目未设置认购流程，请去项目流程菜单配置!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			// 检查流程节点是否已设置人员（认购审批）
			String processKey = startProcessKey_rg;
			boolean isSeting = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), reqDto.getProjectId(), processKey);
			if (!isSeting) {
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("认购审批流程节点人员未设置!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		}

		// 4.2、新增认购
		SubscribeDto subscribeDto = addSubscribeManage.addSubscribe(reqDto);
		if (subscribeDto == null) {
			// 抛出异常
			throw new Exception("subscribe");
		}

		// 4.3、新增认购家庭成员
		if (reqDto.getCustomerFamilyList() != null) {
			List<CustomerFamilyListReq> cusFmReqList = reqDto
					.getCustomerFamilyList();
			commonResDto = addSubscribeManage.addSubscribeFamily(subscribeDto,
					cusFmReqList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}

		/**
		 * 4.4 提交审核
		 *
		 * 1.提交认筹审核,修改状态为审核中,保存流程ID 2.修改房源状态认购
		 */
		String pid = null,flag = null;
		if (reqDto.getDiscountApproval().equals("1")
				&& reqDto.getDiscountApproval() != null && reqDto.getAuditStatus().equals("1")
				&& reqDto.getAuditStatus() != null) {
			// 初始化销控业务异常表
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(subscribeDto.getId());
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_0.getNo());
			businessAbnormaDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			businessAbnormaDto.setAccessCode(subscribeDto.getAccessCode());
			businessAbnormaDto.setUserCode(subscribeDto.getUserCode());
			businessAbnormaDto.setMerchantId(reqDto.getMerchantId());
			businessAbnormaDto.setCreateUserId(Long.valueOf(reqDto.getUserId()));
			businessAbnormaDto.setDelFlag("0");
			businessAbnormaDto.setUpdateUserId(Long.valueOf(reqDto.getUserId()));
			businessAbnormaDto.setUpdateTime(new Date());
			BusinessAbnormaDto baDto = businessAbnormaService.create(businessAbnormaDto);
			if (baDto != null) {
				flag = "1";
				Map<String, Object> variables = new HashMap<String, Object>();
				User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
				identityService.setAuthenticatedUserId(user.getUserAccount());
				pid=activitiProcessService.startProcessInstance(user.getMerchantId(), reqDto.getProjectId(), startProcessKey_rgzk,subscribeDto.getId().toString(), variables);
				BusinessAbnormaDto updateBADto = new BusinessAbnormaDto();
				updateBADto.setId(baDto.getId());
				updateBADto.setProcInstId(pid);
				updateBADto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				businessAbnormaService.update(updateBADto);
				// 修改房源状态为认购
				ProjectRoomDto projectRoomDto = new ProjectRoomDto();
				projectRoomDto.setId(subscribeDto.getRoomId());
				projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());
				projectRoomService.update(projectRoomDto);
			}
		} else if (reqDto.getDiscountApproval().equals("0")
				&& reqDto.getDiscountApproval() != null) {
			if (reqDto.getAuditStatus().equals("1")
					&& reqDto.getAuditStatus() != null) {
				flag = "2";
				Map<String, Object> variables = new HashMap<String, Object>();
				User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
				identityService.setAuthenticatedUserId(user.getUserAccount());
				pid=activitiProcessService.startProcessInstance(user.getMerchantId(),reqDto.getProjectId(), startProcessKey_rg, subscribeDto.getId().toString(), variables);

				SubscribeDto updateDto = new SubscribeDto();
				updateDto.setId(subscribeDto.getId());
				updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				updateDto.setProcInstId(pid);
				subscribeService.update(updateDto);
				// 修改房源状态为认购
				ProjectRoomDto projectRoomDto = new ProjectRoomDto();
				projectRoomDto.setId(subscribeDto.getRoomId());
				projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());
				projectRoomService.update(projectRoomDto);
			}
		}

		// 4.5、新增合同附件【图片】
		if (reqDto.getImageList() != null) {
			List<ImageListReq> imageList = reqDto.getImageList();
			commonResDto = addSubscribeManage.addSubscribeImage(subscribeDto, imageList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("image");
			}
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 修改认购（editSubscribe）
	 */
	@Override
	public EditSubscribeResDto editSubscribe(EditSubscribeReqDto reqDto)
			throws Exception {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、修改认筹
		EditSubscribeResDto resDto = editSubscribeManage.editSubscribe(reqDto);
		if (StringUtils.isNotEmpty(resDto.getErrorCode())
				&& "00001".equals(resDto.getErrorCode())) {
			// 抛出异常
			throw new Exception("editSubscribe");
		}
		return resDto;
	}

	@Override
	public GetSubscribeDetailResDto getSubscribeDetail(
			GetSubscribeDetailReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、认购详情
		return getSubscribeDetailManage.getSubscribeDetail(reqDto);
	}

	/**
	 * getProjectBusinessList:(app查询项目下业务列表接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetProjectBusinessListResDto getProjectBusinessList(
			GetProjectBusinessListReqDto reqDto) {
		GetProjectBusinessListResDto resDto = new GetProjectBusinessListResDto();
		// 客户数据权限校验
		//客户数据权限
		String cus_resource_code = "menu_0006_0001";
		//逾期未签约数据权限
		String sign_resource_code = "menu_0100_0001";
		//逾期未付款数据权限
		String pay_resource_code = "menu_0100_0002";
		String dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), cus_resource_code, "t", null);
		String [] str_permission = dataPermission.split(":");
		if("00".equals(str_permission[0])){
			//无数据权限
			str_permission[1] = " AND 1=2";
		}
		String dataPermissionSigned = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), sign_resource_code, "t", null);
		String [] str_permission_signed = dataPermissionSigned.split(":");
		if("00".equals(str_permission_signed[0])){
			//无数据权限
			str_permission_signed[1] = " AND 1=2";
		}
		String dataPermissionPay = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), pay_resource_code, "t", null);
		String [] str_permission_pay = dataPermissionPay.split(":");
		if("00".equals(str_permission_pay[0])){
			//无数据权限
			str_permission_pay[1] = " AND 1=2";
		}
		ProjectDto dto = new ProjectDto();
		dto.setProjectCode(reqDto.getProjectCode());
		Project project = projectService.selectByDto(dto);
		if (project != null) {
			resDto.setProjectId(String.valueOf(project.getId()));
		}
		// 查询对应统计数量
		CustomerCountDto cusCountDto = new CustomerCountDto();
		cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
		cusCountDto.setProjectCode(reqDto.getProjectCode());
		cusCountDto.setDataPermission(str_permission[1]);
		cusCountDto.setDataPermission_sign(str_permission_signed[1]);
		cusCountDto.setDataPermission_pay(str_permission_pay[1]);
		User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
		cusCountDto.setUserId(String.valueOf(user.getId()));
		cusCountDto.setUserCode(user.getUserCode());
		cusCountDto.setIsAdmin(user.getIsAdmin());
		CustomerTopCount topCount = customerMapper.selectCountByCus(cusCountDto);
		List<HomePageListRes> homePageList = new ArrayList<HomePageListRes>();
		if (topCount != null) {
			/**
			 * 按钮权限
			 */
			UserResourcesDto urButtonDto = new UserResourcesDto();
			urButtonDto.setResourcesLevel("1");
			//app端标示
			urButtonDto.setResourcesType("2");
			urButtonDto.setParentCode("menu_0100");
			urButtonDto.setMerchantId(user.getMerchantId());
			List<Resources> resList = null;
			if(user.getIsAdmin().equals("1")){
				resList = merchantResourcesService.findUserResources(urButtonDto);
			}else{
				urButtonDto.setRoleId(String.valueOf(user.getRoleId()));
				resList = merchantResourcesService.findRoleResources(urButtonDto);
			}
			if(resList.size() > 0){
				for(Resources resources : resList){
					HomePageListRes homePage = new HomePageListRes();
					HomePageListRes homePage2 = new HomePageListRes();
					HomePageListRes homePage3 = new HomePageListRes();
					HomePageListRes homePage4 = new HomePageListRes();
					HomePageListRes homePage5 = new HomePageListRes();
					HomePageListRes homePage6= new HomePageListRes();
					HomePageListRes homePage7 = new HomePageListRes();
					HomePageListRes homePage8 = new HomePageListRes();
					/**
					 * 首页菜单下按钮权限
					 *  父编码parent_code值不为空并且等于menu_0100
					 *  1、resources_code值不为空并且等于menu_0100_0001时，代表有【首页】菜单下有【逾期未签约】按钮权限
					 *  2、resources_code值不为空并且等于menu_0100_0002时，代表有【首页】菜单下有【逾期未付款】按钮权限
					 *  3、resources_code值不为空并且等于menu_0100_0003时，代表有【首页】菜单下有【待处理客户】按钮权限
					 *  4、resources_code值不为空并且等于menu_0100_0004时，代表有【首页】菜单下有【审核申请】按钮权限
					 *  5、resources_code值不为空并且等于menu_0100_0005时，代表有【首页】菜单下有【公告】按钮权限
					 *  6、resources_code值不为空并且等于menu_0100_0006时，代表有【首页】菜单下有【提醒】按钮权限
					 *  7、resources_code值不为空并且等于menu_0100_0007时，代表有【首页】菜单下有【下次跟进提醒】按钮权限
					 *  7、resources_code值不为空并且等于menu_0100_0008时，代表有【首页】菜单下有【未完善客户信息】按钮权限
					 */
					//逾期未签约
					if(resources.getResourcesCode() != null && "menu_0100_0001".equals(resources.getResourcesCode())){
						homePage.setHomePageName("逾期未签约");
						homePage.setHomePageNoReadNum(topCount.getSignedNum());
						homePageList.add(homePage);
					}
					//逾期未付款
					if(resources.getResourcesCode() != null && "menu_0100_0002".equals(resources.getResourcesCode())){
						homePage2.setHomePageName("逾期未付款");
						homePage2.setHomePageNoReadNum(topCount.getPaymentNum());
						homePageList.add(homePage2);
					}
					//签约回款提醒
					if(resources.getResourcesCode() != null && "menu_0100_0009".equals(resources.getResourcesCode())){
						homePageList.add(
								selectNonpaymentNum(reqDto.getMerchantId(),
										Long.parseLong(reqDto.getUserId()),
										reqDto.getProjectId())
						);
					}
					//待处理客户
//					if(resources.getResourcesCode() != null && "menu_0100_0003".equals(resources.getResourcesCode())){
//						homePage3.setHomePageName("待处理客户");
//						homePage3.setHomePageNoReadNum(topCount.getCustomerNum());
//						homePageList.add(homePage3);
//					}
					//审核申请
					if(resources.getResourcesCode() != null && "menu_0100_0004".equals(resources.getResourcesCode())){
						// 审核申请
						List<String> processDefinitionKeys =new ArrayList<String>();
						processDefinitionKeys.add("cusPayDeposit");
						processDefinitionKeys.add("cusSubscribe");
						processDefinitionKeys.add("cusSigned");
//						processDefinitionKeys.add("cusSubscribeDiscount");
//						processDefinitionKeys.add("cusSignedDiscount");
				        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(reqDto.getUserId()).processDefinitionKeyIn(processDefinitionKeys);
						int auditNum = 0;
						if(taskQuery != null){
							auditNum += taskQuery.count();
						}
						if (auditNum == 0) {
							homePage4.setHomePageNoReadNum("0");
						} else {
							homePage4.setHomePageNoReadNum(String.valueOf(auditNum));
						}
						homePage4.setHomePageName("审核申请");
						homePageList.add(homePage4);
					}
					//公告
					if(resources.getResourcesCode() != null && "menu_0100_0005".equals(resources.getResourcesCode())){
						homePage5.setHomePageName("公告");
						homePage5.setHomePageNoReadNum(topCount.getNoticeNum());
						homePageList.add(homePage5);
					}
					//提醒
					if(resources.getResourcesCode() != null && "menu_0100_0006".equals(resources.getResourcesCode())){
						homePage6.setHomePageName("提醒");
						homePage6.setHomePageNoReadNum(topCount.getRemindNum());
						homePageList.add(homePage6);
					}
					//下次跟进提醒
					if(resources.getResourcesCode() != null && "menu_0100_0007".equals(resources.getResourcesCode())){
						homePage7.setHomePageName("下次跟进提醒");
						homePage7.setHomePageNoReadNum(topCount.getNextReminderNum());
						homePageList.add(homePage7);
					}
					//未完善信息客户
					if(resources.getResourcesCode() != null && "menu_0100_0008".equals(resources.getResourcesCode())){
						homePage8.setHomePageName("未完善信息客户");
						homePage8.setHomePageNoReadNum(topCount.getImperfectCustomerNum());
						homePageList.add(homePage8);
					}
				}
			}
		}
		homePageList.add(addTitle("认购"));
		homePageList.add(addTitle("签约"));
		resDto.setHomePageList(homePageList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	/**
	 * 获取签约回款提醒数
	 * @param merchantId
	 * @param userId
	 * @param projectId
	 * @return
	 */
	private HomePageListRes selectNonpaymentNum(Long merchantId, Long userId, Long projectId) {
		HomePageListRes res = new HomePageListRes();
		NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
		dto.setMerchantId(merchantId);
		//判断权限
		if(SysConstants.openDataPermission){
			String dataPermission = dataPermissionService
					.dataPermissionCondition(userId, "menu_0003_0001", null, null);
			String [] dataPermissionArr = dataPermission.split(":");
			dto.setDataPermission(dataPermissionArr[1]);
		}
		int num = needReceiveRefundService.selectNonpaymentNum(dto, projectId, 10);
		res.setHomePageName("签约回款提醒");
		res.setHomePageNoReadNum(String.valueOf(num));
		return res;
	}
	/**
	 * 增加标签项
	 * @param merchantId
	 * @return
	 */
	private HomePageListRes addTitle(String name) {
		HomePageListRes res = new HomePageListRes();
		res.setHomePageName(name);
		res.setHomePageNoReadNum("0");
		return res;
	}

	/**
	 * getMemberScoreList:(app查询会员成绩信息接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param timeType
	 *            时间类型：1、今天（默认）；2、昨天；3、本周；4、上周；5、本月；6、上月；7、近三月；8、今年
	 * @param scoreCategory
	 *            成绩类别：1、置业顾问（个人成绩）；2、案场经理（项目下所有成绩）
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetMemberScoreListResDto getMemberScoreList(
			GetMemberScoreListReqDto reqDto) {
		GetMemberScoreListResDto resDto = new GetMemberScoreListResDto();
		DecimalFormat df = new DecimalFormat("0.00");
		try {
			// 查询对应统计数量
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			cusCountDto.setUserCode(user.getUserCode());
			cusCountDto.setUserId(reqDto.getUserId());
			cusCountDto.setTimeType(reqDto.getTimeType());
			cusCountDto.setScoreCategory(reqDto.getScoreCategory());
			MemberScoreCount scoreCount = customerMapper.selectScoreCountByCus(cusCountDto);
			if (scoreCount != null) {
				resDto.setRcScoreNum(scoreCount.getRcScoreNum());// 认筹数量
				resDto.setRgScoreNum(scoreCount.getRgScoreNum());// 认购数量
				resDto.setQyScoreNum(scoreCount.getQyScoreNum());// 签约数量
				// 认购金额
				if (scoreCount.getSubscribeAmount() != null && !"".equals(scoreCount.getSubscribeAmount())) {
					resDto.setSubscribeAmount(df.format(Double.valueOf(scoreCount.getSubscribeAmount()) / 10000));// 认购金额
				} else {
					resDto.setSubscribeAmount("0");
				}
				// 签约金额
				if (scoreCount.getSignedAmount() != null && !"".equals(scoreCount.getSignedAmount())) {
					resDto.setSignedAmount(df.format(Double.valueOf(scoreCount.getSignedAmount()) / 10000));// 签约金额
				} else {
					resDto.setSignedAmount("0");
				}
				// 回款金额
				if (!"".equals(scoreCount.getReturnAmount()) && scoreCount.getReturnAmount() != null) {
					resDto.setReturnAmount(df.format(Double.valueOf(scoreCount.getReturnAmount()) / 10000));// 回款金额
				} else {
					resDto.setReturnAmount("0");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("查询会员成绩信息失败");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getHeroList:(app查询英雄榜信息接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param timeType
	 *            日期类型：1、今日 【默认】；2、昨日；3、本周；4、上周；5、本月；6、上月；7、三月内；8、全部
	 * @param cusType
	 *            类型：1、认筹；2、认购；3、签约
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetHeroListResDto getHeroList(GetHeroListReqDto reqDto) {
		GetHeroListResDto resDto = new GetHeroListResDto();
		// 查询对应统计数量
		CustomerCountDto cusCountDto = new CustomerCountDto();
		cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
		cusCountDto.setProjectCode(reqDto.getProjectCode());
		cusCountDto.setTimeType(reqDto.getTimeType());
		List<HeroCount> heroCount = null;
		if (reqDto.getCusSort() != null && !"".equals(reqDto.getCusSort())) {
			cusCountDto.setCusSort(reqDto.getCusSort());
			if ("1".equals(reqDto.getCusSort())) {// 按数量统计
				if ("1".equals(reqDto.getCusType())) {// 认筹
					heroCount = customerMapper.selectHeroCountByCusRc(cusCountDto);
				} else if ("2".equals(reqDto.getCusType())) {// 认购
					heroCount = customerMapper.selectHeroCountByCusRg(cusCountDto);
				} else if ("3".equals(reqDto.getCusType())) {// 签约
					heroCount = customerMapper.selectHeroCountByCusQy(cusCountDto);
				}
			} else {// 按金额统计
				if ("1".equals(reqDto.getCusType())) {// 认筹
					heroCount = customerMapper.selectHeroAmountCountByCusRc(cusCountDto);
				} else if ("2".equals(reqDto.getCusType())) {// 认购
					heroCount = customerMapper.selectHeroAmountCountByCusRg(cusCountDto);
				} else if ("3".equals(reqDto.getCusType())) {// 签约
					heroCount = customerMapper.selectHeroAmountCountByCusQy(cusCountDto);
				}
			}
		} else {
			if ("1".equals(reqDto.getCusType())) {// 认筹
				heroCount = customerMapper.selectHeroCountByCusRc(cusCountDto);
			} else if ("2".equals(reqDto.getCusType())) {// 认购
				heroCount = customerMapper.selectHeroCountByCusRg(cusCountDto);
			} else if ("3".equals(reqDto.getCusType())) {// 签约
				heroCount = customerMapper.selectHeroCountByCusQy(cusCountDto);
			}
		}
		List<HeroList> heroList = new ArrayList<HeroList>();
		if (heroCount.size() > 0) {
			for (int i = 0; i < heroCount.size(); i++) {
				HeroList heroEntity = new HeroList();
				heroEntity.setAgent(heroCount.get(i).getAgent());// 经纪人
				heroEntity.setHeadPic(heroCount.get(i).getHeadPic());// 头像
				if (reqDto.getCusSort() != null
						&& !"".equals(reqDto.getCusSort())) {
					if ("1".equals(reqDto.getCusSort())) {
						heroEntity.setCusNum(heroCount.get(i).getCusNum());// 成绩数量
					} else {
						if(heroCount.get(i).getCusAmount() != null && !"".equals(heroCount.get(i).getCusAmount())){
							heroEntity.setCusAmount(df.format(Double.valueOf(heroCount.get(i).getCusAmount())/10000));// 金额
						}else{
							heroEntity.setCusAmount("0");// 金额
						}
					}
				} else {
					heroEntity.setCusNum(heroCount.get(i).getCusNum());// 成绩数量
				}
				if (i == 0) {
					heroEntity.setRanking("冠军");
				} else if (i == 1) {
					heroEntity.setRanking("亚军");
				} else if (i == 2) {
					heroEntity.setRanking("季军");
				}
				heroList.add(heroEntity);
			}
			resDto.setHeroList(heroList);
		} else {
			resDto.setHeroList(null);
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getAuditList:(app查询审核列表接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetAuditListResDto getAuditList(GetAuditListReqDto reqDto) {
		GetAuditListResDto resDto = new GetAuditListResDto();
		int pageNumber = Integer.parseInt(reqDto.getPageNumber())-1;// 页码
		int pageSize = Integer.parseInt(reqDto.getPageSize());// 页码大小
		List<AuditListRes> auditListRes = new ArrayList<AuditListRes>();// 返回待审核List
		// 根据当前人的ID查询
		List<String> processDefinitionKeys =new ArrayList<String>();
		processDefinitionKeys.add("cusPayDeposit");
		processDefinitionKeys.add("cusSubscribe");
		processDefinitionKeys.add("cusSigned");
		processDefinitionKeys.add("FCcusPayDeposit");
		processDefinitionKeys.add("FCcusSubscribe");
		processDefinitionKeys.add("FCcusSigned");
//		processDefinitionKeys.add("cusSubscribeDiscount");
//		processDefinitionKeys.add("cusSignedDiscount");
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(reqDto.getUserId()).processDefinitionKeyIn(processDefinitionKeys);
		List<Task> tasks = taskQuery.orderByTaskCreateTime().desc().listPage(pageNumber, pageSize);
		for(Task t:tasks){
			ProcessInstanceHistoryLog processInstanceHistoryLog=historyService.createProcessInstanceHistoryLogQuery(t.getProcessInstanceId()).singleResult();
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery().processDefinitionId(t.getProcessDefinitionId()).singleResult();
				AuditListRes ar_entity=new AuditListRes();
				if(processDefinition.getName() != null && ("cusPayDeposit".equals(processDefinition.getKey()) || "FCcusPayDeposit".equals(processDefinition.getKey()))){
					ar_entity.setAuditType("认筹");
//				}else if(processDefinition.getName() != null && ("cusSubscribe".equals(processDefinition.getKey()) || "cusSubscribeDiscount".equals(processDefinition.getKey()))){
//					ar_entity.setAuditType("认购");
//				}else if(processDefinition.getName() != null && ("cusSigned".equals(processDefinition.getKey()) || "cusSignedDiscount".equals(processDefinition.getKey()))){
//					ar_entity.setAuditType("签约");
//				}
				}else if(processDefinition.getName() != null && ("cusSubscribe".equals(processDefinition.getKey()) || "FCcusSubscribe".equals(processDefinition.getKey()))){
					ar_entity.setAuditType("认购");
				}else if(processDefinition.getName() != null && ("cusSigned".equals(processDefinition.getKey()) || "FCcusSigned".equals(processDefinition.getKey()))){
					ar_entity.setAuditType("签约");
				}
				ar_entity.setBusinessId(processInstanceHistoryLog.getBusinessKey());
				ar_entity.setCreateTime(sdf.format(t.getCreateTime()));
				ar_entity.setTaskId(t.getId());
				if("cusPayDeposit".equals(processDefinition.getKey()) || "FCcusPayDeposit".equals(processDefinition.getKey())){
					PayDeposit payDeposit = payDepositService.selectById(Long.valueOf(processInstanceHistoryLog.getBusinessKey()));
					if(payDeposit != null){
						ProjectRoom projectRoom = projectRoomService.selectById(payDeposit.getRoomId());
						if (IsPaydepositEnum.YES.getNo().equals(payDeposit.getIsPaydeposit())) {
							ar_entity.setHouses("无房认筹");// 判断是否无房认筹
						} else {
							if (projectRoom != null && projectRoom.getCombinedName() != null) {
								ar_entity.setHouses(projectRoom.getCombinedName());// 认筹房源（有房认筹）
							} else {
								ar_entity.setHouses("无");
							}
						}
						User user = userService.selectById(payDeposit.getAgentId());
						if (user == null) {
							ar_entity.setAgent("无");
						} else {
							ar_entity.setAgent(user.getUserName());// 经纪人
						}
					}
//				}else if("cusSubscribe".equals(processDefinition.getKey()) || "cusSubscribeDiscount".equals(processDefinition.getKey())){
				}else if("cusSubscribe".equals(processDefinition.getKey()) || "FCcusSubscribe".equals(processDefinition.getKey())){
					Subscribe subscribe = subscribeService.selectById(Long.valueOf(processInstanceHistoryLog.getBusinessKey()));
					if(subscribe != null){
						ProjectRoom projectRoom_sub = projectRoomService.selectById(subscribe.getRoomId());
						if (projectRoom_sub == null) {
							ar_entity.setHouses("无");
						} else {
							ar_entity.setHouses(projectRoom_sub.getCombinedName());// 认购房源
						}
						TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
						transactionRelationDto.setBusinessId(subscribe.getId());
						transactionRelationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
						List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
						String agentName = "";
						if(transactionRelationList.size() > 0){
							for(int i=0;i<transactionRelationList.size();i++){
								User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
								if(user.getUserName() != null && !"".equals(user.getUserName())){
									if(transactionRelationList.size() == 1){
										agentName = user.getUserName();
									}else{
										if(i == 0){
											agentName += user.getUserName();
										}else{
											agentName += ","+user.getUserName();
										}
									}
								}
							}
						}
						ar_entity.setAgent(agentName);// 经纪人
					}
//				}else if("cusSigned".equals(processDefinition.getKey()) || "cusSignedDiscount".equals(processDefinition.getKey())){
				}else if("cusSigned".equals(processDefinition.getKey()) || "FCcusSigned".equals(processDefinition.getKey())){
					Signed signed = signedService.selectById(Long.valueOf(processInstanceHistoryLog.getBusinessKey()));
					if(signed != null){
						ProjectRoom projectRoom_sig = projectRoomService.selectById(signed.getRoomId());
						if (projectRoom_sig == null) {
							ar_entity.setHouses("无");
						} else {
							ar_entity.setHouses(projectRoom_sig.getCombinedName());// 签约房源
						}
						TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
						transactionRelationDto.setBusinessId(signed.getId());
						transactionRelationDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
						List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
						String agentName = "";
						if(transactionRelationList.size() > 0){
							for(int i=0;i<transactionRelationList.size();i++){
								User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
								if(user.getUserName() != null && !"".equals(user.getUserName())){
									if(transactionRelationList.size() == 1){
										agentName = user.getUserName();
									}else{
										if(i == 0){
											agentName += user.getUserName();
										}else{
											agentName += ","+user.getUserName();
										}
									}
								}
							}
						}
						ar_entity.setAgent(agentName);// 经纪人
					}
				}
				auditListRes.add(ar_entity);
		}
		if (taskQuery.count() == 0) {
			resDto.setTotalPage("0");
			resDto.setTotalCount("0");
			resDto.setAuditList(null);
		} else {
			int totalPage = setPageSize(pageSize,Integer.valueOf(String.valueOf(taskQuery.count())));
			resDto.setTotalPage(String.valueOf(totalPage));
			resDto.setTotalCount(String.valueOf(taskQuery.count()));
			resDto.setAuditList(auditListRes);
		}
		resDto.setPageNumber(String.valueOf(pageNumber));
		resDto.setPageSize(String.valueOf(pageSize));
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	public static int setPageSize(int pageSize,int total) {
		int totalPages=0;
		if(pageSize>0&&total%pageSize==0){
			totalPages = total/pageSize;
		}else{
			totalPages = (total - total%pageSize)/pageSize + 1;
		}
		return totalPages;
	}

	/**
	 * businessAudit:(app业务审核接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param businessId
	 *            业务Id：用于跳转到对应业务类型（认筹Id；认购Id、签约Id）详情页
	 * @param businessType
	 *            业务类型：认筹，认购，签约（移动端中文做入参）
	 * @param auditStatus
	 *            审核状态：1、审核通过；2、审核驳回
	 * @param remark
	 *            备注
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public BusinessAuditResDto businessAudit(BusinessAuditReqDto reqDto) {
		BusinessAuditResDto resDto = new BusinessAuditResDto();
		try{
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			Task task = taskService.createTaskQuery().taskId(reqDto.getTaskId()).singleResult();
			if (null == task) {
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("审核失败：当前任务不存在！");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			// 保存节点审核状态
			String auditStatus = null;
			if("1".equals(reqDto.getAuditStatus())){
				auditStatus = "0";
			}else if("2".equals(reqDto.getAuditStatus())){
				auditStatus = "1";
			}

			//获取流程参数Id
			Object objectId=runtimeService.getVariable(task.getExecutionId(), "processProjectId");
			if(null==objectId){
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("审核失败：流程参数错误！");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long processProjectId=(Long)objectId;

			 Map<String, Object> globalVariables = new HashMap<String, Object>();
			 globalVariables.put("processCheckStatus", auditStatus);
			 globalVariables.put("nextUserId", "");
			 String nextNodeId=activitiProcessServiceImpl.getNextNodeId(task.getProcessInstanceId());
			 List<String> userIdList = new ArrayList<String>();
			 if(null!=nextNodeId){
				 userIdList=activitiProcessServiceImpl.getNodeUserId(user.getMerchantId(),processProjectId,/*task.getProcessDefinitionId()*/null,nextNodeId);
		   		 if(userIdList.size()>0){
		   			 globalVariables.put("nextUserId", userIdList.get(0));
		   		 }else{
		   			resDto.setErrorCode("0000");
					resDto.setErrorMsg("下一个节点处理人未设置！");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
		   		 }
			 }

			// 保存审批人以及审批意见
			identityService.setAuthenticatedUserId(user.getUserAccount());
			taskService.addComment(reqDto.getTaskId(), task.getProcessInstanceId(), reqDto.getRemark());
			taskService.setVariableLocal(task.getId(), "taskCheckStatus",auditStatus);
			runtimeService.setVariables(task.getExecutionId(),globalVariables);

			// checkStatus 0、成功；1、驳回
			if (auditStatus.equals("0")) {
				// 审批完成，设置
				taskService.complete(task.getId());
				//修改客户交易状态
				if("认筹".equals(reqDto.getBusinessType())){//认筹
					PayDeposit payDeposit = payDepositService.selectById(Long.valueOf(reqDto.getBusinessId()));
					customerService.getCustomerEntity("1", Long.valueOf(reqDto.getBusinessId()),payDeposit.getCustomerId() , user.getId());
				}else if("认购".equals(reqDto.getBusinessType())){//认购
					Subscribe subscribe = subscribeService.selectById(Long.valueOf(reqDto.getBusinessId()));
					customerService.getCustomerEntity("2", Long.valueOf(reqDto.getBusinessId()),subscribe.getCustomerId() , user.getId());
				}else if("签约".equals(reqDto.getBusinessType())){//签约
					Signed signed = signedService.selectById(Long.valueOf(reqDto.getBusinessId()));
					customerService.getCustomerEntity("3", Long.valueOf(reqDto.getBusinessId()),signed.getCustomerId() , user.getId());
				}

			} else if (auditStatus.equals("1")) {
				// 终止流程
				activitiProcessServiceImpl.endProcess(task.getId(),null);
			}
			 sendMessageService.applyMessageSend(task.getProcessInstanceId(),nextNodeId, userIdList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getSignedDetail:(app查看签约详情接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param signId
	 *            签约Id
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetSignedDetailResDto getSignedDetail(GetSignedDetailReqDto reqDto) {
		GetSignedDetailResDto resDto = new GetSignedDetailResDto();
		// 组装查询语句参数
		SignedDto entity = new SignedDto();
		entity.setMerchantId(reqDto.getMerchantId());// 商户Id
		if(!"1".equals(reqDto.getIsAudit())){
			entity.setProjectCode(reqDto.getProjectCode());// 项目Code
		}
		/*User user = userService.selectById(Long.valueOf(reqDto.getUserId()));*/
		entity.setId(Long.valueOf(reqDto.getSignId()));// 签约主键Id
		Signed signed = signedService.selectByDto(entity);
		if (signed == null) {
			resDto.setErrorCode(XFUNExceptionCode.NOSIGNEDDETAIL.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.NOSIGNEDDETAIL.getDesin());
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//业务返回类型： 0   无； 1 认筹； 2 认购
		HaveReceiveRefundDto entity_hrrd = new HaveReceiveRefundDto();
		List<HaveReceiveRefund> resList = null;
		BigDecimal realAmount = new BigDecimal("0");
		if(!"".equals(signed.getSubscribeId()) && signed.getSubscribeId() != null){
			resDto.setBusReturnType("2");
			entity_hrrd.setRelationId(signed.getSubscribeId());
			entity_hrrd.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
			//认筹、认购转签约时,收款记录变成已转账.会找不到收款纪录 2016-10-19_JHSong
//			entity_hrrd.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
//			entity_hrrd.setDocType(DocTypeEnum.COLLECTION.getNo());
			resList = haveReceiveRefundService.selectListByDto(entity_hrrd);
			if(resList != null){
				for(int i = 0; i < resList.size(); i++){
					HaveReceiveRefund have = (HaveReceiveRefund)resList.get(i);
					realAmount = realAmount.add(have.getRealAmount());
				}
				resDto.setRealAmount(String.valueOf(realAmount));
			}else{
				resDto.setRealAmount(null);
			}
		}else{
			if(!"".equals(signed.getPayDepositId()) && signed.getPayDepositId() != null){
				resDto.setBusReturnType("1");
				entity_hrrd.setRelationId(signed.getPayDepositId());
				entity_hrrd.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
//				entity_hrrd.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
//				entity_hrrd.setDocType(DocTypeEnum.COLLECTION.getNo());
				resList = haveReceiveRefundService.selectListByDto(entity_hrrd);
				if(resList != null){
					for(int i = 0; i < resList.size(); i++){
						HaveReceiveRefund have = (HaveReceiveRefund)resList.get(i);
						realAmount = realAmount.add(have.getRealAmount());
					}
					resDto.setRealAmount(String.valueOf(realAmount));
				}else{
					resDto.setRealAmount(null);
				}
			}else{
				resDto.setBusReturnType("0");
			}
		}
		// 认筹编号
		if (!"".equals(signed.getPayDepositCode())
				&& signed.getPayDepositCode() != null) {
			resDto.setPayDepositCode(signed.getPayDepositCode());
		} else {
			resDto.setPayDepositCode(null);
		}
		// 认筹金额
		if (!"".equals(signed.getPayDepositMoney())
				&& signed.getPayDepositMoney() != null) {
			resDto.setPayDepositMoney(String.valueOf(signed
					.getPayDepositMoney()));
		} else {
			resDto.setPayDepositMoney(null);
		}
		// 认购编号
		if (!"".equals(signed.getSubscribeCode())
				&& signed.getSubscribeCode() != null) {
			resDto.setSubscribeCode(signed.getSubscribeCode());
		} else {
			resDto.setSubscribeCode(null);
		}
		// 认购金额
		if (!"".equals(signed.getSubscribeAmount())
				&& signed.getSubscribeAmount() != null) {
			resDto.setSubscribeAmount(String.valueOf(signed
					.getSubscribeAmount()));
		} else {
			resDto.setSubscribeAmount(null);
		}
		// 签约编号
		if (!"".equals(signed.getSignCode()) && signed.getSignCode() != null) {
			resDto.setSignedCode(signed.getSignCode());
		} else {
			resDto.setSignedCode(null);
		}
		// 签约房源
		ProjectRoom projectRoom = projectRoomService.selectById(signed
				.getRoomId());
		if (projectRoom == null) {
			resDto.setSignedHouses("无");
		} else {
			resDto.setSignedHouses(projectRoom.getRoomName());// 签约房源
		}
		// 计价面积
		if (!"".equals(signed.getCalculateArea())
				&& signed.getCalculateArea() != null) {
			resDto.setCalculateArea(String.valueOf(signed.getCalculateArea()));
		} else {
			resDto.setCalculateArea(null);
		}
		// 折前单价
		if (!"".equals(signed.getConversionPrice())
				&& signed.getConversionPrice() != null) {
			resDto.setDiscountPrice(String.valueOf(signed.getConversionPrice()));
		} else {
			resDto.setDiscountPrice(null);
		}
		// 折前总价
		if (!"".equals(signed.getLumpsumPrice())
				&& signed.getLumpsumPrice() != null) {
			/*String discountTotalPrice = df.format(Double.valueOf(String.valueOf(signed.getLumpsumPrice())) / 10000);*/
			String discountTotalPrice = String.valueOf(signed.getLumpsumPrice());
			resDto.setDiscountTotalPrice(discountTotalPrice);
		} else {
			resDto.setDiscountTotalPrice(null);
		}
		// 折扣金额
		if (!"".equals(signed.getDiscountAmount())
				&& signed.getDiscountAmount() != null) {
			resDto.setDiscountAmount(String.valueOf(signed.getDiscountAmount()));
		} else {
			resDto.setDiscountAmount(null);
		}
		// 房间Id
		resDto.setRoomId(String.valueOf(signed.getRoomId()));
		//新增折扣比例
		if(null != signed.getDiscountRate() && !"".equals(signed.getDiscountRate())){
//			resDto.setAddDiscountRate(String.valueOf(signed.getDiscountRate().multiply(new BigDecimal(100))));
			resDto.setAddDiscountRate(String.valueOf(signed.getDiscountRate()));
		}
		//折扣比例：房源对应房间折扣比例
		PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(signed.getRoomId());
		if(priceSchemeDetail != null){
			if(priceSchemeDetail.getDiscountRate() != null && !"".equals(priceSchemeDetail.getDiscountRate())){
				resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate()));
			}else{
				resDto.setDiscountRate(null);
			}
		}
		//推荐人信息
		if(signed.getReferenceName() != null && !"".equals(signed.getReferenceName())){
			resDto.setReferenceName(signed.getReferenceName());
		}
		if(signed.getReferenceProportion() != null && !"".equals(signed.getReferenceProportion())){
			resDto.setReferenceProportion(String.valueOf(signed.getReferenceProportion()));
		}
		// 业务状态
		String businessStatus = signed.getBusinessStatus();
		String businessSecStatus = signed.getBusinessSecStatus();
		resDto.setBusinessStatus(SignedBusinessStatusEnum.getByNo(businessStatus).getDes());
		if(StringUtils.isNotBlank(businessSecStatus)){
			if(SignedBusinessStatusEnum.CHECKWARDS.getNo().equals(businessSecStatus)){
				resDto.setBusinessStatus("签约退房");
			}
		}

		// 折扣审批状态、折扣审批人、折扣审批时间
		String adp_status = null;
		if (signed.getDiscountApproval() != null && "0".equals(signed.getDiscountApproval())) {
			resDto.setDiscountApproval(signed.getDiscountApproval());
			resDto.setDiscountApprovalStatus(null);
			resDto.setDiscountApprovalPeople(null);
			resDto.setDiscountApprovalTime(null);
		} else {
			resDto.setDiscountApproval(signed.getDiscountApproval());
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(signed.getId());// 业务ID
			List<BusinessAbnorma> businessAbnormaList = businessAbnormaService.selectListByDto(businessAbnormaDto);
			if (businessAbnormaList.size() > 0) {
				for (BusinessAbnorma businessAbnorma : businessAbnormaList) {
					adp_status = businessAbnorma.getAuditStatus();
					resDto.setDiscountApprovalStatus(AuditStatusEnum.getByNo(businessAbnorma.getAuditStatus()).getDes());//0待提交 1审核中 2已退回 3已通过
					// 根据proc_inst_id流程实列ID 获取审批人、审批时间
					if(StringUtils.isEmpty(businessAbnorma.getProcInstId())){
						continue;
					}
					List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery()
							.processInstanceId(businessAbnorma.getProcInstId())
							.orderByHistoricActivityInstanceStartTime().desc().list();
					if (instances != null && instances.size() > 0) {
						boolean isEnd = true;
						List<HistoryTaskInfoListRes> userTaskList = new ArrayList<HistoryTaskInfoListRes>();
						for (HistoricActivityInstance historicActivityInstance : instances) {
							if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
								HistoryTaskInfoListRes htf = new HistoryTaskInfoListRes();

								if (historicActivityInstance.getActivityType().equals("startEvent")) {// 开始节点
									ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(historicActivityInstance.getProcessInstanceId()).singleResult();
									htf.setTaskName("启动");
									htf.setTaskUserName(processInstanceHistoryLog.getStartUserId());
									htf.setTaskCheckStatus("发起");
									htf.setStartDate(historicActivityInstance.getStartTime());
									htf.setEndDate(historicActivityInstance.getEndTime());

									userTaskList.add(htf);
									continue;
								}

								if (historicActivityInstance.getActivityType().equals("endEvent")) {// 结束节点
									continue;
								}

								List<Comment> commentList = taskService.getTaskComments(historicActivityInstance
										.getTaskId());
								htf.setTaskName(historicActivityInstance.getActivityName());
								htf.setStartDate(historicActivityInstance.getStartTime());
								htf.setEndDate(historicActivityInstance.getEndTime());
								if (isEnd)// 为最后一个审批节点
									htf.setIsEnd(isEnd);
								if (null != commentList && commentList.size() > 0)
									htf.setTaskUserName(commentList.get(0).getUserId());//审核人
									htf.setAuditReason(commentList.get(0).getFullMessage());//审核意见
								userTaskList.add(htf);
								isEnd = false;
							}
						}

						if (userTaskList.size() > 0) {
							for (HistoryTaskInfoListRes historyTaskInfoVo : userTaskList) {
								if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
								}
								// 获取最后的审批人、审批时间、审批意见
								if (historyTaskInfoVo.getIsEnd() != null && historyTaskInfoVo.getIsEnd()) {
									if(AuditStatusEnum.REJECT.getNo().equals(businessAbnorma.getAuditStatus()) || AuditStatusEnum.SUCCESS.getNo().equals(businessAbnorma.getAuditStatus())){
										UserDto userDto = new UserDto();
										userDto.setUserAccount(historyTaskInfoVo.getTaskUserName());
										User userEntity = userService.selectByDto(userDto);
										resDto.setDiscountApprovalPeople(userEntity.getUserName());//审批人名称
										resDto.setDiscountApprovalTime(sdf.format(historyTaskInfoVo.getEndDate()));//审批时间
									}
								}
							}
						}
					}
				}
			}
		}
		// 优惠原因
		if (signed.getPreferentialReasons() != null) {
			resDto.setPreferentialReasons(signed.getPreferentialReasons());
		} else {
			resDto.setPreferentialReasons(null);
		}
		// 折扣说明
		if (!"".equals(signed.getDiscountNote())
				&& signed.getDiscountNote() != null) {
			resDto.setDiscountNote(String.valueOf(signed.getDiscountNote()));
		} else {
			resDto.setDiscountNote(null);
		}
		// 签约单价
		if (!"".equals(signed.getSignPrice()) && signed.getSignPrice() != null) {
			resDto.setSignPrice(String.valueOf(signed.getSignPrice()));
		} else {
			resDto.setSignPrice(null);
		}
		// 合同金额
		if (!"".equals(signed.getSignAmount())
				&& signed.getSignAmount() != null) {
			/*String contractAmount = df.format(Double.valueOf(String.valueOf(signed.getSignAmount())) / 10000);*/
			String contractAmount = String.valueOf(signed.getSignAmount());
			resDto.setContractAmount(contractAmount);
		} else {
			resDto.setContractAmount(null);
		}
		// 装修款：1、一次性付款；2、分期付款；3、商业按揭；
		if (StringUtils.isNotBlank(signed.getDecorationPaymentMethod())) {
			resDto.setDecorationPaymentMethod(DecorationPaymentMethodEnum.getByNo(signed.getDecorationPaymentMethod()).getDes());
		}
		// 付款方式：1、一次性付款；2、分期付款；3、商业按揭；4、公积金按揭；5、组合贷款
		if (!"".equals(signed.getPaymentMethod()) && signed.getPaymentMethod() != null) {
			resDto.setPaymentMethod(PaymentMethodEnum.getByNo(signed.getPaymentMethod()).getDes());

			String extraInformation=signed.getExtraInformation();
			if(!signed.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getNo()) && StringUtils.isNotBlank(extraInformation)){
				JSONObject object=JSON.parseObject(extraInformation);
				JSONArray paymentDetails=object.getJSONArray("paymentDetails");
				//付款方式
				List<PaymentMethodListRes> pmReqList = new ArrayList<PaymentMethodListRes>();
				//装修款
				List<PaymentMethodListRes> decorationList = new ArrayList<PaymentMethodListRes>();
				for(int i=0;i<paymentDetails.size();i++){
					JSONObject row=paymentDetails.getJSONObject(i);
					PaymentMethodListRes pmReqEntity = new PaymentMethodListRes();
					pmReqEntity.setPayContent(row.getString("receivablesFunds"));//款项名称
					pmReqEntity.setReceivable(row.getString("totalReceivablesAmount"));//应收金额
					pmReqEntity.setRealAmount(row.getString("receivedAmount"));//已收金额
					pmReqEntity.setNotRealAmount(row.getString("needReceivedAmount"));//未收金额
					try {
						Date reDate = sdf.parse(row.getString("receivablesDate"));
						pmReqEntity.setReceivableDate(sdf.format(reDate));//应收日期格式：yyyy-MM-dd
					} catch (ParseException e) {
						e.printStackTrace();
					}
					//分开存储支付方式和装修款
					if(row.getString("receivablesFunds").indexOf("装修款") > 0) {
						decorationList.add(pmReqEntity);
					} else {
						pmReqList.add(pmReqEntity);
					}
				}
				resDto.setPaymentMethodList(pmReqList);
				resDto.setDecorationPaymentMethodList(decorationList);
			}else{
				NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto();
				needReceiveRefundDto.setRelationId(signed.getId());
				//needReceiveRefundDto.setPaymentMethod(signed.getPaymentMethod());
				List<NeedReceiveRefund> needReceiveRefundList = needReceiveRefundService.selectListByDto(needReceiveRefundDto);
				//付款方式
				List<PaymentMethodListRes> pmReqList = new ArrayList<PaymentMethodListRes>();
				//装修款
				List<PaymentMethodListRes> decorationList = new ArrayList<PaymentMethodListRes>();
				if (needReceiveRefundList.size() > 0) {
					for (int n=0;n<needReceiveRefundList.size();n++) {
						NeedReceiveRefund need = (NeedReceiveRefund)needReceiveRefundList.get(n);
						PaymentMethodListRes pmReqEntity = new PaymentMethodListRes();
						String payContent = HousingFundTypeEnum.getByNo(need.getHousingFundType()).getDes();
						pmReqEntity.setPayContent(payContent);// 款项名称
						pmReqEntity.setReceivable(String.valueOf(need.getTotalReceivablesAmount()));// 应收金额
						//已收金额、未收金额
						BigDecimal big = new BigDecimal("0");
						HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
						haveReceiveRefundDto.setReceivablesId(need.getId());
						List<HaveReceiveRefund> list = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
						for (HaveReceiveRefund refund : list) {
							big=big.add(refund.getRealAmount());
						}
		//					if(n == 0){
							//big为已收总金额 = 签约已收金额+认筹或认购已收金额.JHSong_2016-10-26
		//						big = big.add(realAmount);
		//					}
						pmReqEntity.setRealAmount(String.valueOf(big));//已收金额
						pmReqEntity.setNotRealAmount(String.valueOf(need.getTotalReceivablesAmount().subtract(big)));//未收金额
						if(needReceiveRefundList.get(n).getReceivablesDate() != null && !"".equals(need.getReceivablesDate())){
							pmReqEntity.setReceivableDate(sdf.format(need.getReceivablesDate()));// 应收日期格式：yyyy-MM-dd
						}else{
							pmReqEntity.setReceivableDate(null);
						}
						//分开存储支付方式和装修款
						if(payContent.indexOf("装修款") > 0) {
							decorationList.add(pmReqEntity);
						} else {
							pmReqList.add(pmReqEntity);
						}
					}
					resDto.setPaymentMethodList(pmReqList);
					resDto.setDecorationPaymentMethodList(decorationList);
				} else {
					resDto.setPaymentMethodList(null);
				}
			}
			// 成交类别
			if (!"".equals(signed.getDealCategory())
					&& signed.getDealCategory() != null) {
				resDto.setDealCategory(DealCategoryEnum.getByNo(
						signed.getDealCategory()).getDes());
			} else {
				resDto.setDealCategory(null);
			}
			// 签约日期
			if (!"".equals(signed.getDidTime()) && signed.getDidTime() != null) {
				resDto.setSignedDate(sdf.format(signed.getDidTime()));
			} else {
				resDto.setSignedDate(null);
			}
			// 备注
			if (!"".equals(signed.getRemark()) && signed.getRemark() != null) {
				resDto.setRemark(signed.getRemark());
			} else {
				resDto.setRemark(null);
			}
			//方案类别（0 低价；1 折扣）
			if(signed.getFloorType() != null && !"".equals(signed.getFloorType())){
				resDto.setFloorType(signed.getFloorType());
			}else{
				resDto.setFloorType(null);
			}
			//折后金额
			if(signed.getDiscountAfterPrice() != null && !"".equals(signed.getDiscountAfterPrice())){
				resDto.setDiscountAfterAmount(String.valueOf(signed.getDiscountAfterPrice()));
			}else{
				resDto.setDiscountAfterAmount(null);
			}
			/**
			 *0: 折扣低价 1: 折扣比例
			 *计算错误,按照注释下方的内容进行计算
			 *JHSong_2016-10-27_操作: 注释
			 *
			if("1".equals(signed.getFloorType())){
				//计算折后总价
				BigDecimal lumpsumPrice = new BigDecimal(0);
				BigDecimal discountAmount = new BigDecimal(0);
				if(null != signed.getLumpsumPrice()){
					lumpsumPrice = signed.getLumpsumPrice();
				}
				if(null != signed.getDiscountAmount()){
					discountAmount = signed.getDiscountAmount();
				}
				String discountAfterAmount = String.valueOf(lumpsumPrice.subtract(discountAmount));
				resDto.setDiscountAfterAmount(discountAfterAmount);
			}
			*/
			if("0".equals(signed.getFloorType())){
				//计算折后总价
				BigDecimal lumpsumPrice = new BigDecimal(0);
				BigDecimal discountAmount = new BigDecimal(0);
				if(null != signed.getLumpsumPrice()){
					lumpsumPrice = signed.getLumpsumPrice();
				}
				if(null != signed.getDiscountAmount()){
					discountAmount = signed.getDiscountAmount();
				}
				String discountAfterAmount = String.valueOf(lumpsumPrice.subtract(discountAmount));
				resDto.setDiscountAfterAmount(discountAfterAmount);

				//折扣比例：房源对应房间折扣比例
				priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(signed.getRoomId());
				if(priceSchemeDetail != null){
					if(priceSchemeDetail.getDiscountRate() != null && !"".equals(priceSchemeDetail.getDiscountRate())){
						resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate()));
					}else{
						resDto.setDiscountRate(null);
					}
				}
				//JHSong_折扣底价时，从价格方案中获取底价_2016-11-02_代码2100~2107，注释2109
				//resDto.setDiscountRate(String.valueOf(signed.getDiscountRate()));
			}else{
				//折扣比例：房源对应房间折扣比例
				priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(signed.getRoomId());
				if(priceSchemeDetail != null){
//					BigDecimal t2 = new BigDecimal(100);
					if(priceSchemeDetail.getDiscountRate() != null && !"".equals(priceSchemeDetail.getDiscountRate())){
						resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate()));
//						resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate().divide(t2)));
					}else{
						resDto.setDiscountRate(null);
					}
				}
			}


			// 审核状态
			if (!"".equals(signed.getAuditStatus()) && signed.getAuditStatus() != null && "0".equals(signed.getDiscountApproval())  ||  ("1".equals(signed.getDiscountApproval()) &&  !"".equals(adp_status) && adp_status != null && adp_status.equals("3"))) {
				resDto.setAuditStatus(AuditStatusEnum.getByNo(signed.getAuditStatus()).getDes());
			} else if("0".equals(signed.getAuditStatus())){
				resDto.setAuditStatus(AuditStatusEnum.getByNo(signed.getAuditStatus()).getDes());
			}else {
				resDto.setAuditStatus(null);
			}
			// 获取最新的审核数据
			boolean discountApprovalFlag = false;
			if(StringUtils.isBlank(signed.getDiscountApproval()) || "0".equals(signed.getDiscountApproval())){
				discountApprovalFlag = true;
			}
			if((AuditStatusEnum.SUCCESS.getNo().equals(signed.getAuditStatus()) && discountApprovalFlag) || (AuditStatusEnum.REJECT.getNo().equals(signed.getAuditStatus()) && discountApprovalFlag)){
			List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery()
					.processInstanceId(signed.getProcInstId()).orderByHistoricActivityInstanceStartTime().desc().list();
			if (instances != null && instances.size() > 0) {
				boolean isEnd = true;
				List<HistoryTaskInfoListRes> userTaskList = new ArrayList<HistoryTaskInfoListRes>();
				for (HistoricActivityInstance historicActivityInstance : instances) {
					if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
						HistoryTaskInfoListRes htf = new HistoryTaskInfoListRes();

						if (historicActivityInstance.getActivityType().equals(
								"startEvent")) {// 开始节点
							ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
									.createProcessInstanceHistoryLogQuery(
											historicActivityInstance
													.getProcessInstanceId())
									.singleResult();
							htf.setTaskName("启动");
							htf.setTaskUserName(processInstanceHistoryLog
									.getStartUserId());
							htf.setTaskCheckStatus("发起");
							htf.setStartDate(historicActivityInstance
									.getStartTime());
							htf.setEndDate(historicActivityInstance
									.getEndTime());

							userTaskList.add(htf);
							continue;
						}

						if (historicActivityInstance.getActivityType().equals(
								"endEvent")) {// 结束节点
							continue;
						}

						List<Comment> commentList = taskService
								.getTaskComments(historicActivityInstance
										.getTaskId());
						htf.setTaskName(historicActivityInstance
								.getActivityName());
						htf.setStartDate(historicActivityInstance
								.getStartTime());
						htf.setEndDate(historicActivityInstance.getEndTime());
						if (isEnd)// 为最后一个审批节点
							htf.setIsEnd(isEnd);
						if (null != commentList && commentList.size() > 0)
							htf.setTaskUserName(commentList.get(0).getUserId());// 审核人
						htf.setAuditReason(commentList.get(0).getFullMessage());// 审核意见
						userTaskList.add(htf);
						isEnd = false;
					}
				}

				if (userTaskList.size() > 0) {
					for (HistoryTaskInfoListRes historyTaskInfoVo : userTaskList) {
						if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
						}
						// 获取最后的审批人、审批时间、审批意见
						if (historyTaskInfoVo.getIsEnd() != null
								&& historyTaskInfoVo.getIsEnd()) {
								UserDto userDto = new UserDto();
								userDto.setUserAccount(historyTaskInfoVo.getTaskUserName());
								User userEntity = userService.selectByDto(userDto);
								resDto.setAudit(userEntity.getUserName());// 审批人名称
								resDto.setAuditTime(sdf.format(historyTaskInfoVo
										.getEndDate()));// 审批时间
								resDto.setAuditReason(historyTaskInfoVo
										.getAuditReason());// 审批意见
							}
						}
					}
				}
			}
		} else {
			resDto.setPaymentMethod(null);
		}
		// 获取签约客户信息
		Customer customer = customerService.selectById(signed.getCustomerId());
		resDto.setCustomerName(customer.getCustomerName());
		if (StringUtils.isNotEmpty(customer.getCustomerStar())) {
			resDto.setCustomerStar(CustomerStarEnum.getByNo(
					customer.getCustomerStar()).getDes());
		} else {
			resDto.setCustomerStar(null);
		}
		if(StringUtils.isNotEmpty(customer.getCustomerSex())){
			resDto.setCustomerSex(SexEnum.getByNo(customer.getCustomerSex()).getDes());
		}
		resDto.setCustomerPhone(customer.getCustomerPhone());
		if(StringUtils.isNotEmpty(customer.getIntentionLevel())){
			resDto.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
		}
		if(StringUtils.isNotEmpty(customer.getCustomerOrigin())){
			BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
			if(baseCodeValue != null){
				resDto.setCustomerOrigin(baseCodeValue.getCodeName());
			}
		}
		// 客户状态
		if(StringUtils.isNotEmpty(customer.getCustomerStatus())){
			resDto.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
		}
		if (StringUtils.isNotEmpty(customer.getPeDocumentType())) {
			BaseCodeValue baseCodeValue_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getPeDocumentType()));
			if(baseCodeValue_zjlx != null){
				resDto.setDocumentType(baseCodeValue_zjlx.getCodeName());
			}
		}
		resDto.setDocumentNumber(customer.getPeDocumentNumber());
		resDto.setMobile(customer.getCustomerPhone());
		resDto.setMailPost(customer.getPeContactAddress());
		resDto.setPostcode(customer.getPePostcode());

		// 图片列表
		ImageDto imageDto = new ImageDto();
		imageDto.setMerchantId(signed.getMerchantId());
		imageDto.setUserCode(signed.getUserCode());
		imageDto.setObjectId(signed.getId());
		imageDto.setImgType(ImgTypeEnum.SIGNED.getNo());
		List<Image> imageList = imageService.selectListByDto(imageDto);
		List<ImageListRes> imageListRes = new ArrayList<ImageListRes>();
		List<AnnexListRes> annexListRes = new ArrayList<AnnexListRes>();
		if (imageList.size() > 0) {
			int annexNum = 0;
			for (Image image : imageList) {
				//gif|jpg|jpeg|png|bmp|GIF|JPG|JPEG|PNG|BMP图片后缀名格式
				String url_format = image.getSmallUrl();
				String url = url_format.substring(url_format.length()-3);
				String url2 = url_format.substring(url_format.length()-4);
				if("gif".equals(url) || "GIF".equals(url) || "jpg".equals(url) || "JPG".equals(url)
					|| "png".equals(url) || "PNG".equals(url) || "bmp".equals(url)
					|| "BMP".equals(url) || "jpeg".equals(url2) || "JPEG".equals(url2)){
					ImageListRes imageEntity = new ImageListRes();
					imageEntity.setImageId(String.valueOf(image.getId()));
					imageEntity.setTitle(image.getTitle());
					imageEntity.setLargeUrl(image.getLargeUrl());
					imageEntity.setNormalUrl(image.getNormalUrl());
					imageEntity.setSmallUrl(image.getSmallUrl());
					imageListRes.add(imageEntity);
				}else{
					annexNum += 1;
					AnnexListRes annexEntity = new AnnexListRes();
					annexEntity.setAnnexName(image.getTitle());
					annexListRes.add(annexEntity);
				}
			}
			resDto.setAnnexNum(String.valueOf(annexNum));
			resDto.setAnnexList(annexListRes);
			resDto.setImageList(imageListRes);
		} else {
			resDto.setImageList(null);
		}

		//获取成交类别List
		TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
		transactionRelationDto.setBusinessId(signed.getId());
		transactionRelationDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
//		transactionRelationDto.setUserCode(signed.getUserCode());
		List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
		List<DealCategoryListReq> dealCategoryList  = new ArrayList<DealCategoryListReq>();
		if(transactionRelationList.size() > 0){
			for(int r=0;r<transactionRelationList.size();r++){
				DealCategoryListReq dealCategoryListReq = new DealCategoryListReq();
				dealCategoryListReq.setRelationAgentId(String.valueOf(transactionRelationList.get(r).getRelationAgentid()));
				User user_agent = userService.selectById(transactionRelationList.get(r).getRelationAgentid());
				dealCategoryListReq.setRelationAgentName(user_agent.getUserName());
				dealCategoryListReq.setProportionCommission(transactionRelationList.get(r).getProportionCommission());
				dealCategoryList.add(dealCategoryListReq);
			}
			resDto.setDealCategoryList(dealCategoryList);
		}else{
			resDto.setDealCategoryList(null);
		}

		// 家庭成员信息
		FamilyMemberDto fmDto = new FamilyMemberDto();
		fmDto.setBuyId(signed.getId());
		fmDto.setCustomerId(signed.getCustomerId());
		fmDto.setMemberType(MemberTypeEnum.SIGNED.getNo());
		List<FamilyMember> familyMemberList = familyMemberService.selectListByDto(fmDto);
		List<CustomerFamilyListRes> customerFamilyListRes = new ArrayList<CustomerFamilyListRes>();
		if (familyMemberList.size() > 0) {
			for (FamilyMember familyMember : familyMemberList) {
				CustomerFamilyListRes cfListRes = new CustomerFamilyListRes();
				cfListRes.setMemberName(familyMember.getMemberName());// 客户姓名
				// 证件类型
				if (StringUtils.isNotEmpty(familyMember.getDocumentType())) {
					BaseCodeValue baseCodeValue_jtcy_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(familyMember.getDocumentType()));
					if(baseCodeValue_jtcy_zjlx != null){
						cfListRes.setDocumentType(baseCodeValue_jtcy_zjlx.getCodeName());
					}
				}
				// 证件号码
				cfListRes.setDocumentNumber(familyMember.getDocumentNumber());
				customerFamilyListRes.add(cfListRes);
			}
			resDto.setCustomerFamilyList(customerFamilyListRes);
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getSignedList:(app查看签约列表接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param customerId
	 *            客户Id
	 * @param pageNumber
	 *            页码
	 * @param pageSize
	 *            页码大小
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetSignedListResDto getSignedList(GetSignedListReqDto reqDto) {
		GetSignedListResDto resDto = new GetSignedListResDto();
		String pageNumber = reqDto.getPageNumber();// 页码
		String pageSize = reqDto.getPageSize();// 页码大小
		try {
			// 1、获取客户相关的姓名及联系电话
			Customer customer = customerService.selectById(Long
					.parseLong(reqDto.getCustomerId()));
			if (customer != null) {
				resDto.setCustomerName(customer.getCustomerName());
				resDto.setCustomerPhone(customer.getCustomerPhone());
			} else {
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("客户获取失败");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			SignedDto signedDto = new SignedDto();
			signedDto.setMerchantId(reqDto.getMerchantId());
			signedDto.setProjectCode(reqDto.getProjectCode());
			signedDto.setCustomerId(Long.valueOf(reqDto.getCustomerId()));
			signedDto.setOrders(" t.create_time desc ");
			Page<Signed> signedPage = signedService.getPageModel(signedDto,PageUtil.begin(Integer.parseInt(pageNumber),Integer.parseInt(pageSize)),Integer.parseInt(pageSize));
			List<SignedListRes> signedListRes = new ArrayList<SignedListRes>();
			if (signedPage.getRows().size() > 0) {
				List<Signed> signedList = signedPage.getRows();
				for (Signed signed : signedList) {
					SignedListRes signRes = new SignedListRes();
					signRes.setSignedId(String.valueOf(signed.getId()));// 签约Id
					ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());// 关联房间表查询对应房源名称
					if (projectRoom == null) {
						signRes.setSignedHouses("无");
					} else {
						signRes.setSignedHouses(projectRoom.getCombinedName());// 签约房源
					}
					// 签约状态
					if("1".equals(signed.getDiscountApproval())){
						BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
						businessAbnormaDto.setBusinessId(signed.getId());//业务ID
						businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_2.getNo());
						List<BusinessAbnorma> businessAbnormaList = businessAbnormaService.selectListByDto(businessAbnormaDto);
						if(businessAbnormaList.size() > 0){
							for(BusinessAbnorma businessAbnorma : businessAbnormaList){
								if(!"3".equals(businessAbnorma.getAuditStatus())){
									signRes.setAuditStatus(AuditStatusEnum.getByNo(businessAbnorma.getAuditStatus()).getDes());//0待提交 1审核中 2已退回 3已通过
								}else{
									if(signed.getAuditStatus() != null && !"".equals(signed.getAuditStatus())){
										signRes.setAuditStatus(AuditStatusEnum.getByNo(signed.getAuditStatus()).getDes());
									}else{
										signRes.setAuditStatus(null);
									}
								}
							}
						}else{
							if (signed.getAuditStatus() != null && !"".equals(signed.getAuditStatus())) {
								signRes.setAuditStatus(AuditStatusEnum.getByNo(signed.getAuditStatus()).getDes());
							} else {
								signRes.setAuditStatus(null);
							}
						}
					}else{
						if (signed.getAuditStatus() != null && !"".equals(signed.getAuditStatus())) {
							signRes.setAuditStatus(AuditStatusEnum.getByNo(signed.getAuditStatus()).getDes());
						} else {
							signRes.setAuditStatus(null);
						}
					}

					signRes.setRecordBusiness("签约");
					if(AuditStatusEnum.REJECT.getNo().equals(signed.getAuditStatus())){
						signRes.setRecordBusiness("签约驳回");
					}else if(AuditStatusEnum.SUCCESS.getNo().equals(signed.getAuditStatus())){
						String businessStatus = signed.getBusinessStatus();
						String businessSecStatus = signed.getBusinessSecStatus();
						if(StringUtils.isNotBlank(businessSecStatus)){
							if(SignedBusinessStatusEnum.CHECKWARDS.getNo().equals(businessSecStatus)){
								signRes.setRecordBusiness("签约退房");
							}else {
								signRes.setRecordBusiness("签约");
							}
						}else{
							if(SignedBusinessStatusEnum.CHECKWARDS.getNo().equals(businessStatus)){
								signRes.setRecordBusiness("签约退房");
							}else {
								signRes.setRecordBusiness("签约");
							}
						}
					}
					signRes.setSignedTime(sdf.format(signed.getDidTime()));// 签约时间
					signedListRes.add(signRes);
				}
				resDto.setTotalPage(String.valueOf(signedPage.getTotalPages()));
				resDto.setTotalCount(String.valueOf(signedPage.getTotal()));
				resDto.setSignedList(signedListRes);
			} else {
				resDto.setTotalPage("0");
				resDto.setTotalCount("0");
				resDto.setSignedList(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		resDto.setPageNumber(pageNumber);
		resDto.setPageSize(pageSize);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * addSigned:(app新增签约接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public AddSignedResDto addSigned(AddSignedReqDto reqDto) {
		AddSignedResDto resDto = new AddSignedResDto();
		try {
			String roomId = reqDto.getSignedHouses();
			if (StringUtils.isNotEmpty(roomId)) {
				ProjectRoom room = projectRoomService.selectById(Long
						.parseLong(roomId));
				if (room != null) {
					String roomStatus = room.getRoomStatus();
					// 可售或认筹状态可认购
					if(reqDto.getSubscribeId() != null && !"".equals(reqDto.getSubscribeId())){
						if (!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus) && !RoomStatusEnum.BUY.getNo().equals(roomStatus)) {
							resDto.setErrorCode("00000");
							resDto.setErrorMsg("此房源已被"+ RoomStatusEnum.getByNo(roomStatus).getDes()+ ",请选择其他房源!");
							resDto.setResult(ResultEnum.FAILURE.getNo());
							return resDto;
						}
					}else{
						if (!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus)) {
							resDto.setErrorCode("00000");
							resDto.setErrorMsg("此房源已被"+ RoomStatusEnum.getByNo(roomStatus).getDes()+ ",请选择其他房源!");
							resDto.setResult(ResultEnum.FAILURE.getNo());
							return resDto;
						}
					}
				} else {
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("房源不存在");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			String startProcessKey_qyzk = null;
			String startProcessKey_qy = null;
			if (reqDto.getDiscountApproval().equals("1") && reqDto.getDiscountApproval() != null){
				//动态获取签约折扣流程KEY
				startProcessKey_qyzk = activitiProcessService.getProcessKey(reqDto.getMerchantId(), reqDto.getProjectId(), ProcessTypeEnums.PROCESS_KEY_13);
				if(StringUtils.isEmpty(startProcessKey_qyzk)){
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("项目未设置签约折扣流程，请去项目流程菜单配置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
				// 检查流程节点是否已设置人员（签约折扣审批）
				String processKey_diszk = startProcessKey_qyzk;
				boolean isSeting_diszk = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), reqDto.getProjectId(), processKey_diszk);
				if (!isSeting_diszk) {
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("签约折扣审批流程节点人员未设置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			if(reqDto.getDiscountApproval().equals("0") && reqDto.getDiscountApproval() != null){
				//动态获取签约流程KEY
				startProcessKey_qy = activitiProcessService.getProcessKey(reqDto.getMerchantId(), reqDto.getProjectId(), ProcessTypeEnums.PROCESS_KEY_12);
				if(StringUtils.isEmpty(startProcessKey_qy)){
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("项目未设置签约流程，请去项目流程菜单配置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
				// 检查流程节点是否已设置人员（签约审批）
				String processKey = startProcessKey_qy;
				boolean isSeting = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), reqDto.getProjectId(), processKey);
				if (!isSeting) {
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("签约审批流程节点人员未设置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			//校验认购号是否重复
			if(reqDto.getSignedCode() != null && !"".equals(reqDto.getSignedCode())){
				SignedDto sb_dto = new SignedDto();
				sb_dto.setMerchantId(reqDto.getMerchantId());
				sb_dto.setProjectCode(reqDto.getProjectCode());
				sb_dto.setSignCode(reqDto.getSignedCode());
				List<Signed> signedList =  signedService.selectListByDto(sb_dto);
				if(signedList.size() > 0){
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("已经存在该签约号!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}
			// 填充新增签约入参信息
			SignedDto entity = new SignedDto();
			entity.setMerchantId(reqDto.getMerchantId());// 商户Id
			entity.setProjectCode(reqDto.getProjectCode());// 项目Code
			User user = userService
					.selectById(Long.valueOf(reqDto.getUserId()));
			entity.setUserCode(user.getUserCode());// 用户Code
			entity.setAccessCode(reqDto.getProjectCode());// 授权Code
			// 认筹Id
			if (StringUtils.isNotEmpty(reqDto.getPayDepositId())
					&& !"null".equals(reqDto.getPayDepositId())) {
				entity.setPayDepositId(Long.valueOf(reqDto.getPayDepositId()));
			}
			// 认筹Code
			if (StringUtils.isNotEmpty(reqDto.getPayDepositCode())) {
				entity.setPayDepositCode(reqDto.getPayDepositCode());
			}
			// 认筹金额
			if (StringUtils.isNotEmpty(reqDto.getPayDepositMoney())) {
				entity.setPayDepositMoney(BigDecimal.valueOf(Double
						.valueOf(reqDto.getPayDepositMoney())));
			}
			// 认购Id
			if (StringUtils.isNotEmpty(reqDto.getSubscribeId())) {
				entity.setSubscribeId(Long.valueOf(reqDto.getSubscribeId()));
			}
			// 认购Code
			if (StringUtils.isNotEmpty(reqDto.getSubscribeCode())) {
				entity.setSubscribeCode(reqDto.getSubscribeCode());
			}
			// 认购金额
			if (StringUtils.isNotEmpty(reqDto.getSubscribeAmount())) {
				entity.setSubscribeAmount(BigDecimal.valueOf(Double
						.valueOf(reqDto.getSubscribeAmount())));
			}
			// 签约编号
			if (StringUtils.isNotEmpty(reqDto.getSignedCode())) {
				entity.setSignCode(reqDto.getSignedCode());
			}
			// 签约房源：入参roomId（房间Id）
			if (StringUtils.isNotEmpty(reqDto.getSignedHouses())) {
				entity.setRoomId(Long.valueOf(reqDto.getSignedHouses()));
			}
			// 计价面积
			if (StringUtils.isNotEmpty(reqDto.getCalculateArea())) {
				entity.setCalculateArea(BigDecimal.valueOf(Double
						.valueOf(reqDto.getCalculateArea())));
			}
			// 折前单价
			if (StringUtils.isNotEmpty(reqDto.getDiscountPrice())) {
				entity.setConversionPrice(BigDecimal.valueOf(Double
						.valueOf(reqDto.getDiscountPrice())));
			}
			// 折前总价
			if (StringUtils.isNotEmpty(reqDto.getDiscountTotalPrice())) {
				/*entity.setLumpsumPrice(BigDecimal.valueOf(Double.valueOf(reqDto.getDiscountTotalPrice()) * 10000));*/
				entity.setLumpsumPrice(BigDecimal.valueOf(Double.valueOf(reqDto.getDiscountTotalPrice())));
			}
			// 折扣金额
			if (StringUtils.isNotEmpty(reqDto.getDiscountAmount())) {
				entity.setDiscountAmount(BigDecimal.valueOf(Double
						.valueOf(reqDto.getDiscountAmount())));
			}
			// 折扣比例
			if (StringUtils.isNotEmpty(reqDto.getDiscountRate())) {
				entity.setDiscountRate(BigDecimal.valueOf(Double.valueOf(reqDto
						.getDiscountRate())));
			}
			// 业务状态：新增默认‘签约’状态
			entity.setBusinessStatus(SignedBusinessStatusEnum.SIGNED.getNo());
			// 优惠原因
			if (StringUtils.isNotEmpty(reqDto.getPreferentialReasons())) {
				entity.setPreferentialReasons(reqDto.getPreferentialReasons());
			}
			// 是否折扣审批
			entity.setDiscountApproval(reqDto.getDiscountApproval());
			// 折扣说明
			if (StringUtils.isNotEmpty(reqDto.getDiscountNote())) {
				entity.setDiscountNote(reqDto.getDiscountNote());
			}
			// 签约单价
			if (StringUtils.isNotEmpty(reqDto.getContractPrice())) {
				entity.setSignPrice(BigDecimal.valueOf(Double.valueOf(reqDto
						.getContractPrice())));
			}
			// 合同金额
			if (StringUtils.isNotEmpty(reqDto.getContractAmount())) {
				/*BigDecimal signAmount = BigDecimal.valueOf(Double.valueOf(reqDto.getContractAmount()) * 10000);*/
				BigDecimal signAmount = BigDecimal.valueOf(Double.valueOf(reqDto.getContractAmount()));
				entity.setSignAmount(signAmount);
				entity.setReceivableAmount(signAmount);// 应收金额 = 合同金额
			}

			entity.setDealCategory(reqDto.getDealCategory());// 成交类别
			try {
				entity.setDidTime(sdf.parse(reqDto.getSignedDate()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			entity.setContactType(ContactTypeEnum.NORMAL.getNo());// 合同类型：默认正常合同
			// 备注
			if (StringUtils.isNotEmpty(reqDto.getRemark())) {
				entity.setRemark(reqDto.getRemark());
			}
			entity.setAuditStatus(reqDto.getAuditStatus());// 审核状态：0、待审核；1、审核中
			if (StringUtils.isNotEmpty(reqDto.getPaymentMethod())) {
				entity.setPaymentMethod(reqDto.getPaymentMethod());// 付款方式：1、一次性付款；2、分期付款；3、商业按揭；4、公积金按揭；5、组合贷款
			}
			if (StringUtils.isNotEmpty(reqDto.getDecorationPaymentMethod())) {
				entity.setDecorationPaymentMethod(reqDto.getDecorationPaymentMethod());// 装修款：1、一次性付款；2、分期付款；3、商业按揭；
				entity.setDecorationMoney(reqDto.getDecorationMoney()); //装修款
			}
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());// 删除状态：0 未删除
			entity.setCreateUserId(Long.valueOf(reqDto.getUserId()));// 创建人Id
			entity.setCreateTime(new Date());// 创建时间
			entity.setCustomerId(Long.valueOf(reqDto.getCustomerId()));// 客户Id
			entity.setProjectId(reqDto.getProjectId());
			if(reqDto.getFloorType() != null){
				entity.setFloorType(reqDto.getFloorType());//方案类别（0 低价；1 折扣）
			}
			if(null != reqDto.getDiscountAfterAmount() && !"".equals(reqDto.getDiscountAfterAmount())){
				entity.setDiscountAfterPrice(new BigDecimal(reqDto.getDiscountAfterAmount()));//折后金额
			}
			//推荐人信息
			if(StringUtils.isNotEmpty(reqDto.getReferenceId())){
				entity.setReferenceId(Long.valueOf(reqDto.getReferenceId()));
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceName())){
				entity.setReferenceName(reqDto.getReferenceName());
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceProportion())){
				entity.setReferenceProportion(new BigDecimal(reqDto.getReferenceProportion()));
			}
			SignedDto dto = signedService.create(entity);

			if (dto != null) {
				//dealCategoryList（成交类别列表）
				if(reqDto.getDealCategoryList() != null && reqDto.getDealCategoryList().size() >0){
					for(int d=0;d<reqDto.getDealCategoryList().size();d++){
						TransactionRelationDto tranDto = new TransactionRelationDto();
						tranDto.setMerchantId(dto.getMerchantId());
						tranDto.setProjectCode(dto.getProjectCode());
						tranDto.setProjectId(dto.getProjectId());
						tranDto.setBusinessId(dto.getId());
						tranDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
						tranDto.setRelationAgentid(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
						tranDto.setProportionCommission(reqDto.getDealCategoryList().get(d).getProportionCommission());
						User userModel = userService.selectById(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
						tranDto.setUserCode(userModel.getUserCode());
						tranDto.setAccessCode(dto.getAccessCode());
						tranDto.setCreateUserId(dto.getCreateUserId());
						tranDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						transactionRelationService.create(tranDto);
					}
				}

				// 更新客户信息
				CustomerDto customerDto = new CustomerDto();
				customerDto.setId(Long.valueOf(reqDto.getCustomerId()));
				customerDto.setCustomerName(reqDto.getMemberName());
				customerDto.setPeDocumentType(reqDto.getDocumentType());
				customerDto.setPeDocumentNumber(reqDto.getDocumentNumber());
				customerDto.setCustomerPhone(reqDto.getMobile());
				customerDto.setPeContactAddress(reqDto.getMailPost());
				customerDto.setPePostcode(reqDto.getPostcode());
				customerService.update(customerDto);

				// 通过项目Code查找到项目Id
				ProjectDto projectDto = new ProjectDto();
				projectDto.setProjectCode(dto.getProjectCode());
				Project project = projectService.selectByDto(projectDto);
				// 新增签约客户家庭成员记录
				if (reqDto.getCustomerFamilyList() != null) {
					for (int i = 0; i < reqDto.getCustomerFamilyList().size(); i++) {
						FamilyMemberDto fmDto = new FamilyMemberDto();
						fmDto.setCustomerId(dto.getCustomerId());// 客户Id
						if (project != null) {
							fmDto.setProjectId(project.getId());// 项目Id
						}
						fmDto.setProjectCode(dto.getProjectCode());// 项目Code
						fmDto.setBuyId(dto.getId());// 购房记录Id：签约Id
						fmDto.setMemberName(reqDto.getCustomerFamilyList()
								.get(i).getMemberName());// 客户姓名
						fmDto.setSex(SexEnum.UNKNOW.getNo());// 新增默认：性别‘未知’
						fmDto.setDocumentType(reqDto.getCustomerFamilyList()
								.get(i).getDocumentType());// 证件类型
						fmDto.setDocumentNumber(reqDto.getCustomerFamilyList()
								.get(i).getDocumentNumber());// 证件号码
						fmDto.setMobile(reqDto.getCustomerFamilyList().get(i)
								.getMobile());// 手机号码
						fmDto.setMailPost(reqDto.getCustomerFamilyList().get(i)
								.getMailPost());// 邮寄地址
						fmDto.setPostcode(reqDto.getCustomerFamilyList().get(i)
								.getPostcode());// 邮编
						fmDto.setMemberType(reqDto.getCustomerFamilyList()
								.get(i).getMemberType());// 成员类型：默认值传 4 （签约客户）
						// 第一个家庭成员默认为第一
						if (i == 0) {
							fmDto.setIsDefault("1");
						} else {
							fmDto.setIsDefault("0");
						}
						fmDto.setMerchantId(dto.getMerchantId());// 商户Id
						fmDto.setUserCode(dto.getUserCode());// 用户Code
						fmDto.setAccessCode(dto.getAccessCode());// 授权Code
						fmDto.setCreateUserId(dto.getCreateUserId());// 创建人Id
						fmDto.setCreateTime(new Date());// 创建时间
						fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());// 删除标识：0
																	// 未删除
						FamilyMember familyMember = familyMemberService
								.create(fmDto);
						if (familyMember == null) {
							resDto.setErrorCode(XFUNExceptionCode.NOADDSIGNEDFAMILYMEMBER
									.getCode());
							resDto.setErrorMsg(XFUNExceptionCode.NOADDSIGNEDFAMILYMEMBER
									.getDesin());
							resDto.setResult(ResultEnum.FAILURE.getNo());
							return resDto;
						}
					}
				}
				// 新增签约合同附件（拍照签约图片）
				List<ImageListReq> ImgList = reqDto.getImageList();
				if (ImgList != null) {
					for (ImageListReq req : ImgList) {
						String imgName = SequencesGenerator.getUUID("IMG")
								+ req.getHeadType();
						String result = FileUploadPorxyUtil.appPost(
								fileUploadUrl, req.getSignedUrl(), imgName);
						JSONObject resultJson = JSON.parseObject(result);
						String postResult = resultJson.getString("result");
						if (!"1".equals(postResult)) {
							resDto.setResult(ResultEnum.FAILURE.getNo());
							resDto.setErrorCode("00000");
							resDto.setErrorMsg("签约合同附件图片上传失败");
							return resDto;
						}
						String postUrl = resultJson.getString("url");
						ImageDto imageDto = new ImageDto();
						imageDto.setObjectId(dto.getId());
						imageDto.setSmallUrl(postUrl);
						imageDto.setImgType(ImgTypeEnum.SIGNED.getNo());
						imageDto.setMerchantId(dto.getMerchantId());
						imageDto.setUserCode(dto.getUserCode());
						imageDto.setAccessCode(dto.getAccessCode());
						imageDto.setRemark("签约合同附件");
						imageDto.setCreateUserId(dto.getCreateUserId());
						imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						imageService.create(imageDto);
					}
				}

				/**
				 * 1.提交认筹审核,修改状态为审核中,保存流程ID 2.修改房源状态签约
				 */
				@SuppressWarnings("unused")
				String pid=null,flag = null;
				if (reqDto.getDiscountApproval().equals("1")
						&& reqDto.getDiscountApproval() != null && reqDto.getAuditStatus().equals("1")
						&& reqDto.getAuditStatus() != null) {
					// 初始化销控业务异常表
					BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
					businessAbnormaDto.setBusinessId(dto.getId());
					businessAbnormaDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
					businessAbnormaDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
					businessAbnormaDto.setAccessCode(dto.getAccessCode());
					businessAbnormaDto.setUserCode(dto.getUserCode());
					businessAbnormaDto.setMerchantId(reqDto.getMerchantId());
					businessAbnormaDto.setCreateUserId(Long.valueOf(reqDto.getUserId()));
					businessAbnormaDto.setDelFlag("0");
					businessAbnormaDto.setUpdateUserId(Long.valueOf(reqDto.getUserId()));
					businessAbnormaDto.setUpdateTime(new Date());
					BusinessAbnormaDto baDto = businessAbnormaService.create(businessAbnormaDto);
					if (baDto != null) {
						flag = "2";
						Map<String, Object> variables = new HashMap<String, Object>();
						identityService.setAuthenticatedUserId(user.getUserAccount());
						pid=activitiProcessService.startProcessInstance(user.getMerchantId(), reqDto.getProjectId(), startProcessKey_qyzk, dto.getId().toString(), variables);
						BusinessAbnormaDto updateBADto = new BusinessAbnormaDto();
						updateBADto.setId(baDto.getId());
						updateBADto.setProcInstId(pid);
						updateBADto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
						businessAbnormaService.update(updateBADto);

						//签约绑定流程ID
						//JHSong，2016-09-06
						dto.setProcInstId(pid);
						signedService.update(dto);

						// 修改房源状态为签约
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setId(dto.getRoomId());
						projectRoomDto.setRoomStatus(RoomStatusEnum.SIGN.getNo());
						projectRoomService.update(projectRoomDto);
					}
				} else if (reqDto.getDiscountApproval().equals("0")
						&& reqDto.getDiscountApproval() != null) {
					if (reqDto.getAuditStatus().equals("1")
							&& reqDto.getAuditStatus() != null) {
						flag = "2";
						Map<String, Object> variables = new HashMap<String, Object>();
						identityService.setAuthenticatedUserId(user.getUserAccount());
						pid=activitiProcessService.startProcessInstance(user.getMerchantId(), reqDto.getProjectId(), startProcessKey_qy, dto.getId().toString(), variables);

						//签约绑定流程ID
						//JHSong，2016-09-06
						dto.setProcInstId(pid);
						signedService.update(dto);

						// 修改房源状态为签约
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setId(dto.getRoomId());
						projectRoomDto.setRoomStatus(RoomStatusEnum.SIGN.getNo());
						projectRoomService.update(projectRoomDto);
					}
				}

				//添加消息（提交审核时，推送push审核消息）
				if ("1".equals(reqDto.getAuditStatus())) {
					if(pid != null){
						dto.setProcInstId(pid);
					}
				}

				//认购金额
				BigDecimal realAmount_rc = new BigDecimal("0");
				BigDecimal realAmount_rg = new BigDecimal("0");
				if(!"".equals(dto.getSubscribeId()) && dto.getSubscribeId() != null){
					HaveReceiveRefundDto entity_hrrd = new HaveReceiveRefundDto();
					entity_hrrd.setRelationId(dto.getSubscribeId());
					entity_hrrd.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
					entity_hrrd.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
					entity_hrrd.setDocType(DocTypeEnum.COLLECTION.getNo());
					List<HaveReceiveRefund> resList = haveReceiveRefundService.selectListByDto(entity_hrrd);
					if(resList != null){
						for(int i = 0; i < resList.size(); i++){
							HaveReceiveRefund have = (HaveReceiveRefund)resList.get(i);
							realAmount_rg = realAmount_rg.add(have.getRealAmount());
						}
					}else{
						realAmount_rg = new BigDecimal("0");
					}
				}else{
					realAmount_rg = new BigDecimal("0");
				}
				//已收认筹金额
				if(!"".equals(dto.getPayDepositId()) && dto.getPayDepositId() != null){
					HaveReceiveRefundDto entity_hrrd2 = new HaveReceiveRefundDto();
					entity_hrrd2.setRelationId(dto.getPayDepositId());
					entity_hrrd2.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
					entity_hrrd2.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
					entity_hrrd2.setDocType(DocTypeEnum.COLLECTION.getNo());
					List<HaveReceiveRefund> resList2 = haveReceiveRefundService.selectListByDto(entity_hrrd2);
					if(resList2 != null){
						for(int i = 0; i < resList2.size(); i++){
							HaveReceiveRefund have2 = (HaveReceiveRefund)resList2.get(i);
							realAmount_rc = realAmount_rc.add(have2.getRealAmount());
						}
					}else{
						realAmount_rc = new BigDecimal("0");
					}
				}else{
					realAmount_rc = new BigDecimal("0");
				}

				JSONObject object=new JSONObject();
				object.put("depositAmount", realAmount_rc);
				object.put("subscribeAmount", realAmount_rg);

				JSONArray array=new JSONArray();
				// 保存应收款
				if(reqDto.getPaymentMethodList().size() > 0){
					for (int i = 0; i < reqDto.getPaymentMethodList().size(); i++) {
						JSONObject row=new JSONObject();
						String receivablesFunds = null;
						String housingFundType = null;
						String businessFlag = null;

						/**
						 * 房款类型、业务标志
						 */
						//认筹转入签约
						if(dto.getPayDepositMoney() != null && PaymentMethodEnum.LUMP_SUM.getNo().equals(dto.getPaymentMethod())){
							receivablesFunds = HousingFundTypeEnum.FUNDTYPE_5.getDes();
							housingFundType = HousingFundTypeEnum.FUNDTYPE_5.getNo();
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(dto.getPayDepositMoney() != null && PaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_6.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_6.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_7.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_7.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(dto.getPayDepositMoney() != null && PaymentMethodEnum.PROVIDENT_FUND_MORTGAGE.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_10.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_10.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_11.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_11.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(dto.getPayDepositMoney() != null && PaymentMethodEnum.COMBINED_LOAN.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_17.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_17.getNo();
							}else if("银行按揭".equals(reqDto.getPaymentMethodList().get(i).getPayContent())  || "按揭银行".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){

								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_18.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_18.getNo();
							}else if("公积金".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_19.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_19.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(dto.getPayDepositMoney() != null && PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(dto.getPaymentMethod())){
							if("一期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_12.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_12.getNo();
							}else if("二期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_13.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_13.getNo();
							}else if("三期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_14.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_14.getNo();
							}else if("四期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_15.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_15.getNo();
							}else if("五期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_16.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_16.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						//认购转入签约
						}else if(dto.getSubscribeAmount() != null && PaymentMethodEnum.LUMP_SUM.getNo().equals(dto.getPaymentMethod())){
							receivablesFunds = HousingFundTypeEnum.FUNDTYPE_5.getDes();
							housingFundType = HousingFundTypeEnum.FUNDTYPE_5.getNo();
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(dto.getSubscribeAmount() != null && PaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_6.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_6.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_7.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_7.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(dto.getSubscribeAmount() != null && PaymentMethodEnum.PROVIDENT_FUND_MORTGAGE.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_10.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_10.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_11.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_11.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(dto.getSubscribeAmount() != null && PaymentMethodEnum.COMBINED_LOAN.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_17.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_17.getNo();
							}else if("银行按揭".equals(reqDto.getPaymentMethodList().get(i).getPayContent()) || "按揭银行".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_18.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_18.getNo();
							}else if("公积金".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_19.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_19.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(dto.getSubscribeAmount() != null && PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(dto.getPaymentMethod())){
							if("一期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_12.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_12.getNo();
							}else if("二期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_13.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_13.getNo();
							}else if("三期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_14.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_14.getNo();
							}else if("四期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_15.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_15.getNo();
							}else if("五期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_16.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_16.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						//一次性付款
						}else if(dto.getSubscribeAmount() == null && dto.getPayDepositMoney() == null && PaymentMethodEnum.LUMP_SUM.getNo().equals(dto.getPaymentMethod())){
							receivablesFunds = HousingFundTypeEnum.FUNDTYPE_5.getDes();
							housingFundType = HousingFundTypeEnum.FUNDTYPE_5.getNo();
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//商业按揭
						}else if(dto.getSubscribeAmount() == null && dto.getPayDepositMoney() == null && PaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_6.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_6.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_7.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_7.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//公积金按揭
						}else if(dto.getSubscribeAmount() == null && dto.getPayDepositMoney() == null && PaymentMethodEnum.PROVIDENT_FUND_MORTGAGE.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_10.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_10.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_11.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_11.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//分期付款
						}else if(dto.getSubscribeAmount() == null && dto.getPayDepositMoney() == null && PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(dto.getPaymentMethod())){
							if("一期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_12.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_12.getNo();
							}else if("二期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_13.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_13.getNo();
							}else if("三期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_14.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_14.getNo();
							}else if("四期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_15.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_15.getNo();
							}else if("五期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_16.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_16.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//组合贷款
						}else if(dto.getSubscribeAmount() == null && dto.getPayDepositMoney() == null && PaymentMethodEnum.COMBINED_LOAN.getNo().equals(dto.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_17.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_17.getNo();
							}else if("银行按揭".equals(reqDto.getPaymentMethodList().get(i).getPayContent()) || "按揭银行".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_18.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_18.getNo();
							}else if("公积金".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_19.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_19.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						}
						if(i==0){
							row.put("receivedAmount", realAmount_rg.add(realAmount_rc));//已收金额
							row.put("needReceivedAmount", BigDecimal.valueOf(Double.valueOf(reqDto.getPaymentMethodList().get(i).getReceivable())).subtract(realAmount_rg.add(realAmount_rc)));//未收金额
						}else{
							String realAmount = null;
							if(reqDto.getPaymentMethodList().get(i).getRealAmount() == null){
								realAmount = "0";
							}else{
								realAmount = reqDto.getPaymentMethodList().get(i).getRealAmount();
							}
							row.put("receivedAmount",  realAmount);//已收金额
							row.put("needReceivedAmount", BigDecimal.valueOf(Double.valueOf(reqDto.getPaymentMethodList().get(i).getReceivable())).subtract(BigDecimal.valueOf(Double.valueOf(realAmount))));//未收金额
						}
						row.put("receivablesFunds", receivablesFunds);//款项
						row.put("totalReceivablesAmount", reqDto.getPaymentMethodList().get(i).getReceivable());//应收金额
						String receivableDate = reqDto.getPaymentMethodList().get(i).getReceivableDate()+" 00:00:00";
						row.put("receivablesDate", receivableDate);//应收日期
						row.put("orgName", "");//银行单位
						row.put("agentName", "");//经办人
						row.put("businessFlag", businessFlag);//业务标志
						row.put("housingFundType", housingFundType);//放款类型
						array.add(row);
					}
					//设置装修款
					if(reqDto.getDecorationPaymentMethodList() != null) {

						decoration(reqDto.getDecorationPaymentMethod(), reqDto.getDecorationPaymentMethodList(), array);
					}
					object.put("paymentDetails", array);
					SignedDto entity_update = new SignedDto();
					entity_update.setId(dto.getId());
					entity_update.setExtraInformation(object.toJSONString());
					signedService.update(entity_update);
				}
			} else {
				resDto.setErrorCode(XFUNExceptionCode.NOADDSIGNED.getCode());
				resDto.setErrorMsg(XFUNExceptionCode.NOADDSIGNED.getDesin());
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("新增签约失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	/**
	 * 设置装修款
	 * @param decorationPaymentMethod
	 * @param list
	 * @param array
	 */
	private void decoration(String decorationPaymentMethod,
			List<PaymentMethodListRes> list, JSONArray array) {
		String receivablesFunds = null;
		String housingFundType = null;
		for(PaymentMethodListRes res : list) {
			//一次性付款
			if(DecorationPaymentMethodEnum.LUMP_SUM.getNo().equals(decorationPaymentMethod)) {
				receivablesFunds = HousingFundTypeEnum.FUNDTYPE_26.getDes();
				housingFundType = HousingFundTypeEnum.FUNDTYPE_26.getNo();
			}else if(DecorationPaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(decorationPaymentMethod)) {
				//分期付款
				if("一期款".equals(res.getPayContent())) {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_29.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_29.getNo();
				}else if("二期款".equals(res.getPayContent())) {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_30.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_30.getNo();
				}else if("三期款".equals(res.getPayContent())) {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_31.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_31.getNo();
				}else if("四期款".equals(res.getPayContent())) {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_32.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_32.getNo();
				}else if("五期款".equals(res.getPayContent())) {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_33.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_33.getNo();
				}
			}else if(DecorationPaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(decorationPaymentMethod)) {
				//商业按揭
				if("首付款".equals(res.getPayContent())) {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_27.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_27.getNo();
				} else {
					receivablesFunds = HousingFundTypeEnum.FUNDTYPE_28.getDes();
					housingFundType = HousingFundTypeEnum.FUNDTYPE_28.getNo();
				}
			}
			JSONObject row=new JSONObject();
			row.put("receivedAmount",  "0");//已收金额
			row.put("needReceivedAmount", res.getNotRealAmount());//未收金额
			row.put("receivablesFunds", receivablesFunds);//款项
			row.put("totalReceivablesAmount", res.getReceivable());//应收金额
			String receivableDate = res.getReceivableDate()+" 00:00:00";
			row.put("receivablesDate", receivableDate);//应收日期
			row.put("orgName", "");//银行单位
			row.put("agentName", "");//经办人
			row.put("businessFlag", BusinessFlagEnum.BUSINESSFLAG_19.getNo());//业务标志
			row.put("housingFundType", housingFundType);//放款类型
			array.add(row);
		}
	}
	/**
	 * editSigned:(app修改签约接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public EditSignedResDto editSigned(EditSignedReqDto reqDto) {
		EditSignedResDto resDto = new EditSignedResDto();
		try {
			// 通过签约Id查询签约信息
			Signed signed = signedService.selectById(Long.valueOf(reqDto.getSignedId()));

			String roomId = reqDto.getSignedHouses();
			if (StringUtils.isNotEmpty(roomId)) {
				ProjectRoom room = projectRoomService.selectById(Long.parseLong(roomId));
				if (room != null) {
					String roomStatus = room.getRoomStatus();
					// 可售或认筹状态可认购
					if(signed.getSubscribeId() != null && !"".equals(signed.getSubscribeId())){
						if (!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus) && !RoomStatusEnum.BUY.getNo().equals(roomStatus)) {
							resDto.setErrorCode("00000");
							resDto.setErrorMsg("此房源已被"+ RoomStatusEnum.getByNo(roomStatus).getDes()+ ",请选择其他房源!");
							resDto.setResult(ResultEnum.FAILURE.getNo());
							return resDto;
						}
					}else{
						if (!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus)) {
							resDto.setErrorCode("00000");
							resDto.setErrorMsg("此房源已被"+ RoomStatusEnum.getByNo(roomStatus).getDes()+ ",请选择其他房源!");
							resDto.setResult(ResultEnum.FAILURE.getNo());
							return resDto;
						}
					}
				} else {
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("房源不存在");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			String startProcessKey_qyzk = null;
			String startProcessKey_qy = null;
			if (reqDto.getDiscountApproval().equals("1") && reqDto.getDiscountApproval() != null){
				//动态获取签约折扣流程KEY
				startProcessKey_qyzk = activitiProcessService.getProcessKey(reqDto.getMerchantId(), signed.getProjectId(), ProcessTypeEnums.PROCESS_KEY_13);
				if(StringUtils.isEmpty(startProcessKey_qyzk)){
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("项目未设置签约折扣流程，请去项目流程菜单配置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
				// 检查流程节点是否已设置人员（签约折扣审批）
				String processKey_diszk = startProcessKey_qyzk;
				boolean isSeting_diszk = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), signed.getProjectId(), processKey_diszk);
				if (!isSeting_diszk) {
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("签约折扣审批流程节点人员未设置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			if(reqDto.getDiscountApproval().equals("0") && reqDto.getDiscountApproval() != null){
				//动态获取签约流程KEY
				startProcessKey_qy = activitiProcessService.getProcessKey(reqDto.getMerchantId(), signed.getProjectId(), ProcessTypeEnums.PROCESS_KEY_12);
				if(StringUtils.isEmpty(startProcessKey_qy)){
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("项目未设置签约流程，请去项目流程菜单配置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
				// 检查流程节点是否已设置人员（签约审批）
				String processKey = startProcessKey_qy;
				boolean isSeting = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), signed.getProjectId(), processKey);
				if (!isSeting) {
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("签约审批流程节点人员未设置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			//校验签约号是否重复
			if(reqDto.getSignedCode() != null && !"".equals(reqDto.getSignedCode())){
				if(!reqDto.getSignedCode().equals(signed.getSignCode())){
					SignedDto sb_dto = new SignedDto();
					sb_dto.setMerchantId(reqDto.getMerchantId());
					sb_dto.setProjectCode(reqDto.getProjectCode());
					sb_dto.setSignCode(reqDto.getSignedCode());
					List<Signed> signedList =  signedService.selectListByDto(sb_dto);
					if(signedList.size() > 0){
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("已经存在该签约号!");
						resDto.setResult(ResultEnum.FAILURE.getNo());
						return resDto;
					}
				}
			}
			// 填充新增签约入参信息
			SignedDto entity = new SignedDto();
			entity.setMerchantId(reqDto.getMerchantId());// 商户Id
			entity.setProjectCode(reqDto.getProjectCode());// 项目Code
			User user = userService
					.selectById(Long.valueOf(reqDto.getUserId()));
			entity.setUserCode(user.getUserCode());// 用户Code
			entity.setAccessCode(reqDto.getProjectCode());// 授权Code
			// 认筹Id
			if (StringUtils.isNotEmpty(reqDto.getPayDepositId())) {
				entity.setPayDepositId(Long.valueOf(reqDto.getPayDepositId()));
			}
			// 认筹Code
			if (StringUtils.isNotEmpty(reqDto.getPayDepositCode())) {
				entity.setPayDepositCode(reqDto.getPayDepositCode());
			}
			// 认筹金额
			if (StringUtils.isNotEmpty(reqDto.getPayDepositMoney())) {
				entity.setPayDepositMoney(BigDecimal.valueOf(Double
						.valueOf(reqDto.getPayDepositMoney())));
			}
			// 认购Id
			if (StringUtils.isNotEmpty(reqDto.getSubscribeId())) {
				entity.setSubscribeId(Long.valueOf(reqDto.getSubscribeId()));
			}
			// 认购Code
			if (StringUtils.isNotEmpty(reqDto.getSubscribeCode())) {
				entity.setSubscribeCode(reqDto.getSubscribeCode());
			}
			// 认购金额
			if (StringUtils.isNotEmpty(reqDto.getSubscribeAmount())) {
				entity.setSubscribeAmount(BigDecimal.valueOf(Double
						.valueOf(reqDto.getSubscribeAmount())));
			}
			// 签约编号
			if (StringUtils.isNotEmpty(reqDto.getSignedCode())) {
				entity.setSignCode(reqDto.getSignedCode());
			}
			// 签约房源：入参roomId（房间Id）
			if (StringUtils.isNotEmpty(reqDto.getSignedHouses())) {
				entity.setRoomId(Long.valueOf(reqDto.getSignedHouses()));
			}
			// 计价面积
			if (StringUtils.isNotEmpty(reqDto.getCalculateArea())) {
				entity.setCalculateArea(BigDecimal.valueOf(Double
						.valueOf(reqDto.getCalculateArea())));
			}
			// 折前单价
			if (StringUtils.isNotEmpty(reqDto.getDiscountPrice())) {
				entity.setConversionPrice(BigDecimal.valueOf(Double
						.valueOf(reqDto.getDiscountPrice())));
			}
			// 折前总价
			if (StringUtils.isNotEmpty(reqDto.getDiscountTotalPrice())) {
				/*entity.setLumpsumPrice(BigDecimal.valueOf(Double.valueOf(reqDto.getDiscountTotalPrice()) * 10000));*/
				entity.setLumpsumPrice(BigDecimal.valueOf(Double.valueOf(reqDto.getDiscountTotalPrice())));
			}
			// 折扣金额
			if (StringUtils.isNotEmpty(reqDto.getDiscountAmount())) {
				entity.setDiscountAmount(BigDecimal.valueOf(Double
						.valueOf(reqDto.getDiscountAmount())));
			}
			// 折扣比例
			if (StringUtils.isNotEmpty(reqDto.getDiscountRate())) {
				entity.setDiscountRate(BigDecimal.valueOf(Double.valueOf(reqDto
						.getDiscountRate())));
			}
			// 优惠原因
			if (StringUtils.isNotEmpty(reqDto.getPreferentialReasons())) {
				entity.setPreferentialReasons(reqDto.getPreferentialReasons());
			}
			// 是否折扣审批
			entity.setDiscountApproval(reqDto.getDiscountApproval());
			// 折扣说明
			if (StringUtils.isNotEmpty(reqDto.getDiscountNote())) {
				entity.setDiscountNote(reqDto.getDiscountNote());
			}
			// 签约单价
			if (StringUtils.isNotEmpty(reqDto.getContractPrice())) {
				entity.setSignPrice(BigDecimal.valueOf(Double.valueOf(reqDto
						.getContractPrice())));
			}
			// 合同金额
			if (StringUtils.isNotEmpty(reqDto.getContractAmount())) {
				/*entity.setSignAmount(BigDecimal.valueOf(Double.valueOf(reqDto.getContractAmount()) * 10000));*/
				entity.setSignAmount(BigDecimal.valueOf(Double.valueOf(reqDto.getContractAmount())));
			}
			entity.setDealCategory(reqDto.getDealCategory());// 成交类别
			try {
				entity.setDidTime(sdf.parse(reqDto.getSignedDate()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			entity.setContactType(ContactTypeEnum.NORMAL.getNo());// 合同类型：默认正常合同
			// 备注
			if (StringUtils.isNotEmpty(reqDto.getRemark())) {
				entity.setRemark(reqDto.getRemark());
			}
			entity.setAuditStatus(reqDto.getAuditStatus());// 审核状态：0、待审核；1、审核中
			if (StringUtils.isNotEmpty(reqDto.getPaymentMethod())) {
				entity.setPaymentMethod(reqDto.getPaymentMethod());// 付款方式：1、一次性付款；2、分期付款；3、商业按揭；4、公积金按揭；5、组合贷款
			}
			if (StringUtils.isNotEmpty(reqDto.getDecorationPaymentMethod())) {
				entity.setDecorationPaymentMethod(reqDto.getDecorationPaymentMethod());// 装修款：1、一次性付款；2、分期付款；3、商业按揭；
				entity.setDecorationMoney(reqDto.getDecorationMoney()); //装修款
			}
			entity.setUpdateUserId(Long.valueOf(reqDto.getUserId()));// 修改人Id
			entity.setUpdateTime(new Date());// 修改时间
			entity.setId(Long.valueOf(reqDto.getSignedId()));// 签约主键Id
			if(reqDto.getFloorType() != null){
				entity.setFloorType(reqDto.getFloorType());//方案类别（0 低价；1 折扣）
			}
			if(null != reqDto.getDiscountAfterAmount() && !"".equals(reqDto.getDiscountAfterAmount())){
				entity.setDiscountAfterPrice(new BigDecimal(reqDto.getDiscountAfterAmount()));//折后金额
			}
			//推荐人信息
			if(StringUtils.isNotEmpty(reqDto.getReferenceId())){
				entity.setReferenceId(Long.valueOf(reqDto.getReferenceId()));
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceName())){
				entity.setReferenceName(reqDto.getReferenceName());
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceProportion())){
				entity.setReferenceProportion(new BigDecimal(reqDto.getReferenceProportion()));
			}
			int updateCount = signedService.update(entity);
			//将签约记录中的支付方式进行覆盖~否则修改时,总是会使用第一次添加的记录
			//JHSong_2016-10-19 11:04:56
			signed.setPaymentMethod(entity.getPaymentMethod());

			// 更新客户信息
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(signed.getCustomerId());
			customerDto.setCustomerName(reqDto.getMemberName());
			customerDto.setPeDocumentType(reqDto.getDocumentType());
			customerDto.setPeDocumentNumber(reqDto.getDocumentNumber());
			customerDto.setCustomerPhone(reqDto.getMobile());
			customerDto.setPeContactAddress(reqDto.getMailPost());
			customerDto.setPePostcode(reqDto.getPostcode());
			customerService.update(customerDto);

			if (updateCount > 0) {
				/**
				 * dealCategoryList（成交类别列表）
				 * 1、先删除原来记录
				 * 2、再新增现有记录
				 */
				if(reqDto.getDealCategoryList() != null && reqDto.getDealCategoryList().size() >0){
					TransactionRelationDto tranRelaDto = new TransactionRelationDto();
					tranRelaDto.setBusinessId(signed.getId());
					transactionRelationService.destroy(tranRelaDto);

					for(int d=0;d<reqDto.getDealCategoryList().size();d++){
						TransactionRelationDto tranDto = new TransactionRelationDto();
						tranDto.setMerchantId(signed.getMerchantId());
						tranDto.setProjectCode(signed.getProjectCode());
						tranDto.setProjectId(signed.getProjectId());
						tranDto.setBusinessId(signed.getId());
						tranDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
						tranDto.setRelationAgentid(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
						tranDto.setProportionCommission(reqDto.getDealCategoryList().get(d).getProportionCommission());
						User userModel = userService.selectById(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
						tranDto.setUserCode(userModel.getUserCode());
						tranDto.setAccessCode(signed.getAccessCode());
						tranDto.setCreateUserId(signed.getCreateUserId());
						tranDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						transactionRelationService.create(tranDto);
					}

				}
				// 通过项目Code查找到项目Id
				ProjectDto projectDto = new ProjectDto();
				projectDto.setProjectCode(reqDto.getProjectCode());
				Project project = projectService.selectByDto(projectDto);

				//认购金额
				BigDecimal realAmount_rc = new BigDecimal("0");
				BigDecimal realAmount_rg = new BigDecimal("0");
				if(!"".equals(signed.getSubscribeId()) && signed.getSubscribeId() != null){
					HaveReceiveRefundDto entity_hrrd = new HaveReceiveRefundDto();
					entity_hrrd.setRelationId(signed.getSubscribeId());
					entity_hrrd.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
					entity_hrrd.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
					entity_hrrd.setDocType(DocTypeEnum.COLLECTION.getNo());
					List<HaveReceiveRefund> resList = haveReceiveRefundService.selectListByDto(entity_hrrd);
					if(resList != null){
						for(int i = 0; i < resList.size(); i++){
							HaveReceiveRefund have = (HaveReceiveRefund)resList.get(i);
							realAmount_rg = realAmount_rg.add(have.getRealAmount());
						}
					}else{
						realAmount_rg = new BigDecimal("0");
					}
				}else{
					realAmount_rg = new BigDecimal("0");
				}
				//已收认筹金额
				if(!"".equals(signed.getPayDepositId()) && signed.getPayDepositId() != null){
					HaveReceiveRefundDto entity_hrrd2 = new HaveReceiveRefundDto();
					entity_hrrd2.setRelationId(signed.getPayDepositId());
					entity_hrrd2.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
					entity_hrrd2.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
					entity_hrrd2.setDocType(DocTypeEnum.COLLECTION.getNo());
					List<HaveReceiveRefund> resList2 = haveReceiveRefundService.selectListByDto(entity_hrrd2);
					if(resList2 != null){
						for(int i = 0; i < resList2.size(); i++){
							HaveReceiveRefund have2 = (HaveReceiveRefund)resList2.get(i);
							realAmount_rc = realAmount_rc.add(have2.getRealAmount());
						}
					}else{
						realAmount_rc = new BigDecimal("0");
					}
				}else{
					realAmount_rc = new BigDecimal("0");
				}

				JSONObject object=new JSONObject();
				object.put("depositAmount", realAmount_rc);
				object.put("subscribeAmount", realAmount_rg);

				JSONArray array=new JSONArray();
				// 保存应收款
				if(reqDto.getPaymentMethodList().size() > 0){
					for (int i = 0; i < reqDto.getPaymentMethodList().size(); i++) {
						JSONObject row=new JSONObject();
						String receivablesFunds = null;
						String housingFundType = null;
						String businessFlag = null;

						/**
						 * 房款类型、业务标志
						 */
						//认筹转入签约
						if(signed.getPayDepositMoney() != null && PaymentMethodEnum.LUMP_SUM.getNo().equals(signed.getPaymentMethod())){
							receivablesFunds = HousingFundTypeEnum.FUNDTYPE_5.getDes();
							housingFundType = HousingFundTypeEnum.FUNDTYPE_5.getNo();
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(signed.getPayDepositMoney() != null && PaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_6.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_6.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_7.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_7.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(signed.getPayDepositMoney() != null && PaymentMethodEnum.PROVIDENT_FUND_MORTGAGE.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_10.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_10.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_11.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_11.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(signed.getPayDepositMoney() != null && PaymentMethodEnum.COMBINED_LOAN.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_17.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_17.getNo();
							}else if("银行按揭".equals(reqDto.getPaymentMethodList().get(i).getPayContent()) || "按揭银行".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_18.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_18.getNo();
							}else if("公积金".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_19.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_19.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						}else if(signed.getPayDepositMoney() != null && PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(signed.getPaymentMethod())){
							if("一期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_12.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_12.getNo();
							}else if("二期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_13.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_13.getNo();
							}else if("三期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_14.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_14.getNo();
							}else if("四期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_15.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_15.getNo();
							}else if("五期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_16.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_16.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_12.getNo();
						//认购转入签约
						}else if(signed.getSubscribeAmount() != null && PaymentMethodEnum.LUMP_SUM.getNo().equals(signed.getPaymentMethod())){
							receivablesFunds = HousingFundTypeEnum.FUNDTYPE_5.getDes();
							housingFundType = HousingFundTypeEnum.FUNDTYPE_5.getNo();
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(signed.getSubscribeAmount() != null && PaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_6.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_6.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_7.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_7.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(signed.getSubscribeAmount() != null && PaymentMethodEnum.PROVIDENT_FUND_MORTGAGE.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_10.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_10.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_11.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_11.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(signed.getSubscribeAmount() != null && PaymentMethodEnum.COMBINED_LOAN.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_17.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_17.getNo();
							}else if("银行按揭".equals(reqDto.getPaymentMethodList().get(i).getPayContent()) || "按揭银行".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_18.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_18.getNo();
							}else if("公积金".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_19.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_19.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						}else if(signed.getSubscribeAmount() != null && PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(signed.getPaymentMethod())){
							if("一期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_12.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_12.getNo();
							}else if("二期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_13.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_13.getNo();
							}else if("三期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_14.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_14.getNo();
							}else if("四期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_15.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_15.getNo();
							}else if("五期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_16.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_16.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_13.getNo();
						//一次性付款
						}else if(signed.getSubscribeAmount() == null && signed.getPayDepositMoney() == null && PaymentMethodEnum.LUMP_SUM.getNo().equals(signed.getPaymentMethod())){
							receivablesFunds = HousingFundTypeEnum.FUNDTYPE_5.getDes();
							housingFundType = HousingFundTypeEnum.FUNDTYPE_5.getNo();
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//商业按揭
						}else if(signed.getSubscribeAmount() == null && signed.getPayDepositMoney() == null && PaymentMethodEnum.COMMERCIAL_MORTGAGE.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_6.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_6.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_7.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_7.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//公积金按揭
						}else if(signed.getSubscribeAmount() == null && signed.getPayDepositMoney() == null && PaymentMethodEnum.PROVIDENT_FUND_MORTGAGE.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_10.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_10.getNo();
							}else{
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_11.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_11.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//分期付款
						}else if(signed.getSubscribeAmount() == null && signed.getPayDepositMoney() == null && PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo().equals(signed.getPaymentMethod())){
							if("一期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_12.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_12.getNo();
							}else if("二期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_13.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_13.getNo();
							}else if("三期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_14.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_14.getNo();
							}else if("四期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_15.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_15.getNo();
							}else if("五期款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_16.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_16.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						//组合贷款
						}else if(signed.getSubscribeAmount() == null && signed.getPayDepositMoney() == null && PaymentMethodEnum.COMBINED_LOAN.getNo().equals(signed.getPaymentMethod())){
							if("首付款".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_17.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_17.getNo();
							}else if("银行按揭".equals(reqDto.getPaymentMethodList().get(i).getPayContent()) || "按揭银行".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_18.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_18.getNo();
							}else if("公积金".equals(reqDto.getPaymentMethodList().get(i).getPayContent())){
								receivablesFunds = HousingFundTypeEnum.FUNDTYPE_19.getDes();
								housingFundType = HousingFundTypeEnum.FUNDTYPE_19.getNo();
							}
							businessFlag = BusinessFlagEnum.BUSINESSFLAG_9.getNo();
						}
						if(i==0){
							row.put("receivedAmount", realAmount_rg.add(realAmount_rc));//已收金额
							row.put("needReceivedAmount", BigDecimal.valueOf(Double.valueOf(reqDto.getPaymentMethodList().get(i).getReceivable())).subtract(realAmount_rg.add(realAmount_rc)));//未收金额
						}else{
							String realAmount = null;
							if(reqDto.getPaymentMethodList().get(i).getRealAmount() == null){
								realAmount = "0";
							}else{
								realAmount = reqDto.getPaymentMethodList().get(i).getRealAmount();
							}
							row.put("receivedAmount",  realAmount);//已收金额
							row.put("needReceivedAmount", BigDecimal.valueOf(Double.valueOf(reqDto.getPaymentMethodList().get(i).getReceivable())).subtract(BigDecimal.valueOf(Double.valueOf(realAmount))));//未收金额
						}
						row.put("receivablesFunds", receivablesFunds);//款项
						row.put("totalReceivablesAmount", reqDto.getPaymentMethodList().get(i).getReceivable());//应收金额
						String receivableDate = reqDto.getPaymentMethodList().get(i).getReceivableDate()+" 00:00:00";
						row.put("receivablesDate", receivableDate);//应收日期
						row.put("orgName", "");//银行单位
						row.put("agentName", "");//经办人
						row.put("businessFlag", businessFlag);//业务标志
						row.put("housingFundType", housingFundType);//放款类型
						array.add(row);
					}
					//设置装修款
					if(reqDto.getDecorationPaymentMethodList() != null) {
						decoration(reqDto.getDecorationPaymentMethod(), reqDto.getDecorationPaymentMethodList(), array);
					}
					object.put("paymentDetails", array);
					SignedDto entity_update = new SignedDto();
					entity_update.setId(signed.getId());
					entity_update.setExtraInformation(object.toJSONString());
					signedService.update(entity_update);
				}

				/**
				 *  新增签约客户家庭成员记录
				 *  修改家庭成员记录前，先通过状态位删除原有记录，再新增
				 */
				if (reqDto.getCustomerFamilyList() != null) {
					FamilyMemberDto fmDto_update = new FamilyMemberDto();
					fmDto_update.setBuyId(signed.getId());
					List<FamilyMember> familyMemberList = familyMemberService.selectListByDto(fmDto_update);
					if(familyMemberList != null && familyMemberList.size() > 0){
						for(FamilyMember familyMember : familyMemberList){
							FamilyMemberDto fmDto_del = new FamilyMemberDto();
							fmDto_del.setId(familyMember.getId());
							familyMemberService.destroy(fmDto_del);
						}
					}

					for (int i = 0; i < reqDto.getCustomerFamilyList().size(); i++) {
						FamilyMemberDto fmDto = new FamilyMemberDto();
						fmDto.setCustomerId(signed.getCustomerId());// 客户Id
						if (project != null) {
							fmDto.setProjectId(project.getId());// 项目Id
						}
						fmDto.setProjectCode(reqDto.getProjectCode());// 项目Code
						fmDto.setBuyId(Long.valueOf(reqDto.getSignedId()));// 购房记录Id：签约Id
						fmDto.setMemberName(reqDto.getCustomerFamilyList()
								.get(i).getMemberName());// 客户姓名
						fmDto.setSex(SexEnum.UNKNOW.getNo());// 新增默认：性别‘未知’
						fmDto.setDocumentType(reqDto.getCustomerFamilyList()
								.get(i).getDocumentType());// 证件类型
						fmDto.setDocumentNumber(reqDto.getCustomerFamilyList()
								.get(i).getDocumentNumber());// 证件号码
						fmDto.setMobile(reqDto.getCustomerFamilyList().get(i)
								.getMobile());// 手机号码
						fmDto.setMailPost(reqDto.getCustomerFamilyList().get(i)
								.getMailPost());// 邮寄地址
						fmDto.setPostcode(reqDto.getCustomerFamilyList().get(i)
								.getPostcode());// 邮编
						fmDto.setMemberType("4");// 成员类型：默认值传 4 （签约客户）
						// 第一个家庭成员默认为第一
						if (i == 0) {
							fmDto.setIsDefault("1");
						} else {
							fmDto.setIsDefault("0");
						}
						fmDto.setMerchantId(reqDto.getMerchantId());// 商户Id
						fmDto.setUserCode(user.getUserCode());// 用户Code
						fmDto.setAccessCode(reqDto.getProjectCode());// 授权Code
						fmDto.setCreateUserId(Long.valueOf(reqDto.getUserId()));// 创建人Id
						fmDto.setCreateTime(new Date());// 创建时间
						fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());// 删除标识：0
																	// 未删除
						FamilyMember familyMember = familyMemberService
								.create(fmDto);
						if (familyMember == null) {
							resDto.setErrorCode(XFUNExceptionCode.NOADDSIGNEDFAMILYMEMBER
									.getCode());
							resDto.setErrorMsg(XFUNExceptionCode.NOADDSIGNEDFAMILYMEMBER
									.getDesin());
							resDto.setResult(ResultEnum.FAILURE.getNo());
							return resDto;
						}
					}
				}
				/*
				 * 修改签约合同附件（拍照签约图片） 1、先根据签约Id把图片表中对应的图片都做状态删除：标记为已删除
				 * 2、再重新新增合同附件图片记录到图片表中
				 */
				List<ImageListReq> imgList = reqDto.getImageList();
				if (imgList != null) {
					// 上传头像后缀名：例如【.jpg】（如入参为0 则代表图片保持不变；入参为 1 则代表改图片做删除）
					for (ImageListReq req : imgList) {
						if ("1".equals(req.getHeadType())) {
							ImageDto dto_img = new ImageDto();
							dto_img.setSmallUrl(req.getSignedUrl());
							imageService.destroy(dto_img);
						} else if (!"1".equals(req.getHeadType())
								&& !"0".equals(req.getHeadType())) {
							String imgName = SequencesGenerator.getUUID("IMG")
									+ req.getHeadType();
							String result = FileUploadPorxyUtil.appPost(
									fileUploadUrl, req.getSignedUrl(), imgName);
							JSONObject resultJson = JSON.parseObject(result);
							String postResult = resultJson.getString("result");
							if (!"1".equals(postResult)) {
								resDto.setResult(ResultEnum.FAILURE.getNo());
								resDto.setErrorCode("00000");
								resDto.setErrorMsg("签约合同附件图片修改上传失败");
								return resDto;
							}
							String postUrl = resultJson.getString("url");
							ImageDto imageDto = new ImageDto();
							imageDto.setObjectId(Long.valueOf(reqDto
									.getSignedId()));
							imageDto.setSmallUrl(postUrl);
							imageDto.setImgType(ImgTypeEnum.SIGNED.getNo());
							imageDto.setMerchantId(reqDto.getMerchantId());
							imageDto.setUserCode(user.getUserCode());
							imageDto.setAccessCode(reqDto.getProjectCode());
							imageDto.setRemark("签约合同附件");
							imageDto.setCreateUserId(Long.valueOf(reqDto
									.getUserId()));
							imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							imageService.create(imageDto);
						}
					}
				}

				/**
				 * 1.提交认筹审核,修改状态为审核中,保存流程ID 2.修改房源状态签约
				 */
				@SuppressWarnings("unused")
				String pid = null,flag = null;
				if (reqDto.getDiscountApproval().equals("1")
						&& reqDto.getDiscountApproval() != null && reqDto.getAuditStatus().equals("1")
						&& reqDto.getAuditStatus() != null) {
					// 初始化销控业务异常表
					BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
					businessAbnormaDto.setBusinessId(signed.getId());
					businessAbnormaDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
					businessAbnormaDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
					businessAbnormaDto.setAccessCode(signed.getAccessCode());
					businessAbnormaDto.setUserCode(signed.getUserCode());
					businessAbnormaDto.setMerchantId(reqDto.getMerchantId());
					businessAbnormaDto.setCreateUserId(Long.valueOf(reqDto.getUserId()));
					businessAbnormaDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					businessAbnormaDto.setUpdateUserId(Long.valueOf(reqDto.getUserId()));
					businessAbnormaDto.setUpdateTime(new Date());
					BusinessAbnormaDto baDto = businessAbnormaService.create(businessAbnormaDto);
					if (baDto != null) {
						flag = "1";
						Map<String, Object> variables = new HashMap<String, Object>();
						identityService.setAuthenticatedUserId(user.getUserAccount());
						pid=activitiProcessService.startProcessInstance(user.getMerchantId(), signed.getProjectId(), startProcessKey_qyzk, signed.getId().toString(), variables);

						BusinessAbnormaDto updateBADto = new BusinessAbnormaDto();
						updateBADto.setId(baDto.getId());
						updateBADto.setProcInstId(pid);
						updateBADto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
						businessAbnormaService.update(updateBADto);

						// 修改房源状态为签约
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setId(signed.getRoomId());
						projectRoomDto.setRoomStatus(RoomStatusEnum.SIGN.getNo());
						projectRoomService.update(projectRoomDto);
					}
				} else if (reqDto.getDiscountApproval().equals("0")
						&& reqDto.getDiscountApproval() != null) {
					if (reqDto.getAuditStatus().equals("1")
							&& reqDto.getAuditStatus() != null) {
						flag = "2";
						Map<String, Object> variables = new HashMap<String, Object>();

						identityService.setAuthenticatedUserId(user.getUserAccount());
						pid=activitiProcessService.startProcessInstance(user.getMerchantId(), signed.getProjectId(), startProcessKey_qy, signed.getId().toString(), variables);

						SignedDto sign_entity = new SignedDto();
						sign_entity.setId(signed.getId());
						sign_entity.setProcInstId(pid);
						sign_entity.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
						signedService.update(sign_entity);

						// 修改房源状态为签约
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setId(signed.getRoomId());
						projectRoomDto.setRoomStatus(RoomStatusEnum.SIGN.getNo());
						projectRoomService.update(projectRoomDto);
					}
				}

				//添加消息（提交审核时，推送push审核消息）
				if ("1".equals(reqDto.getAuditStatus())) {
					if(pid != null){
						signed.setProcInstId(pid);
					}
				}

			} else {
				resDto.setErrorCode(XFUNExceptionCode.NOADDSIGNED.getCode());
				resDto.setErrorMsg(XFUNExceptionCode.NOADDSIGNED.getDesin());
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("修改签约失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getWorkloadStatisticsList:(app查询工作量统计接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 */
	@Override
	public GetWorkloadStatisticsListResDto getWorkloadStatisticsList(
			GetWorkloadStatisticsListReqDto reqDto) {
		GetWorkloadStatisticsListResDto resDto = new GetWorkloadStatisticsListResDto();
		CustomerCountDto customerCountDto = new CustomerCountDto();
		customerCountDto.setTimeType(reqDto.getWorkloadTimeType());// 工作量时间类型
		customerCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));// 商家Id
		customerCountDto.setProjectCode(reqDto.getProjectCode());// 项目code
		List<WorkloadCount> workloadCount_list = customerMapper.selectWorkloadCountByCus(customerCountDto);
		List<WorkloadStatisticsList> workloadStatisticsList = new ArrayList<WorkloadStatisticsList>();
		if (workloadCount_list.size() > 0) {
			for (int i = 0; i < workloadCount_list.size(); i++) {
				WorkloadStatisticsList wkEntity = new WorkloadStatisticsList();
				wkEntity.setUserName(workloadCount_list.get(i).getUserName());// 用户名称
				wkEntity.setFollowNum(workloadCount_list.get(i).getFollowCount());// 跟进数
				wkEntity.setAddCustomerNum(workloadCount_list.get(i).getAddCus());// 新增客户数
				wkEntity.setPayDepositNum(workloadCount_list.get(i).getPayDepositCount());// 认筹数
				wkEntity.setSubscribeNum(workloadCount_list.get(i).getSubscribeCount());// 认购数
				wkEntity.setSignedNum(workloadCount_list.get(i).getSignedCount());// 签约数
				workloadStatisticsList.add(wkEntity);
			}
			resDto.setWorkloadStatisticsList(workloadStatisticsList);
		} else {
			resDto.setWorkloadStatisticsList(null);
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getCustomerAnalysisList:(app查询客户分析接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 */
	@Override
	public GetCustomerAnalysisListResDto getCustomerAnalysisList(
			GetCustomerAnalysisListReqDto reqDto) {
		GetCustomerAnalysisListResDto resDto = new GetCustomerAnalysisListResDto();
		List<CusAnalysisListRes> cusResList = new ArrayList<CusAnalysisListRes>();
		CustomerCountDto customerCountDto = new CustomerCountDto();
		customerCountDto.setProjectCode(reqDto.getProjectCode());
		customerCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
		customerCountDto.setTimeType(reqDto.getTimeType());
		customerCountDto.setCategoryType(reqDto.getCategoryType());
		String[] terminalInfos = reqDto.getTerminalCode().split("\\|");
		if ("2".equals(terminalInfos[1])) {
			customerCountDto.setTerminalType("2");// 设备类型：iOS
		} else {
			customerCountDto.setTerminalType("1");// 设备类型：android
		}
		List<CusAnalysisListRes> cusCountList = customerMapper.selectCustomerAnalysisCountByCus(customerCountDto);
		if (cusCountList.size() > 0) {
			for (int i = 0; i < cusCountList.size(); i++) {
				CusAnalysisListRes cusResEntity = new CusAnalysisListRes();
				cusResEntity.setAnalysisValue(cusCountList.get(i).getAnalysisValue());
				cusResEntity.setAnalysisValuePercentage(cusCountList.get(i).getAnalysisValuePercentage());
				cusResList.add(cusResEntity);
			}
		} else {
			resDto.setCusAnalysisList(null);
		}
		resDto.setCusAnalysisList(cusResList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getCustomerVisitAnalysisList:(app查询客户来访分析接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 */
	@Override
	public GetCustomerVisitAnalysisListResDto getCustomerVisitAnalysisList(
			GetCustomerVisitAnalysisListReqDto reqDto) {
		GetCustomerVisitAnalysisListResDto resDto = new GetCustomerVisitAnalysisListResDto();
		try {
			List<CusVisitAnalysisListRes> cusVisitAnalysisList = new ArrayList<CusVisitAnalysisListRes>();
			CustomerCountDto customerCountDto = new CustomerCountDto();
			customerCountDto.setProjectCode(reqDto.getProjectCode());
			customerCountDto.setMerchantId(String.valueOf(reqDto
					.getMerchantId()));
			customerCountDto.setVisitTimeType(reqDto.getVisitTimeType());
			List<CusVisitAnalysisListRes> cusVisitListRes = customerMapper
					.selectCustomerVisitAnalysisCountByCus(customerCountDto);
			if (cusVisitListRes.size() > 0) {
				for (int i = 0; i < cusVisitListRes.size(); i++) {
					CusVisitAnalysisListRes cusVisitEntity = new CusVisitAnalysisListRes();
					cusVisitEntity.setVisitAnalysisValue(cusVisitListRes.get(i)
							.getVisitAnalysisValue());
					cusVisitEntity.setVisitAnalysisValueNum(cusVisitListRes
							.get(i).getVisitAnalysisValueNum());
					cusVisitAnalysisList.add(cusVisitEntity);
				}
				resDto.setCusVisitAnalysisList(cusVisitAnalysisList);
			} else {
				resDto.setCusVisitAnalysisList(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getGroupHeroList:(app查询销售组英雄榜信息接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param timeType
	 *            日期类型：1、今日 【默认】；2、昨日；3、本周；4、上周；5、本月；6、上月；7、三月内；8、全部
	 * @param cusType
	 *            类型：1、按数量【默认】；2、按金额
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetGroupHeroListResDto getGroupHeroList(GetGroupHeroListReqDto reqDto) {
		GetGroupHeroListResDto resDto = new GetGroupHeroListResDto();
		List<GroupHeroListRes> groupHeroList = new ArrayList<GroupHeroListRes>();// 认筹
		List<GroupHeroSubListRes> groupHeroSubList = new ArrayList<GroupHeroSubListRes>();// 认购
		List<GroupHeroSignedListRes> groupHeroSignedList = new ArrayList<GroupHeroSignedListRes>();// 签约
		try {
			// 查询对应统计数量
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			cusCountDto.setTimeType(reqDto.getTimeType());
			List<HeroCount> heroCount_rc = null;
			List<HeroCount> heroCount_rg = null;
			List<HeroCount> heroCount_qy = null;
			if ("1".equals(reqDto.getCusType())) {// 按数量
				heroCount_rc = customerMapper.selectGroupHeroCountByCusRc(cusCountDto);
				heroCount_rg = customerMapper.selectGroupHeroCountByCusRg(cusCountDto);
				heroCount_qy = customerMapper.selectGroupHeroCountByCusQy(cusCountDto);
			} else if ("2".equals(reqDto.getCusType())) {// 按金额
				heroCount_rc = customerMapper.selectGroupHeroAmountCountByCusRc(cusCountDto);
				heroCount_rg = customerMapper.selectGroupHeroAmountCountByCusRg(cusCountDto);
				heroCount_qy = customerMapper.selectGroupHeroAmountCountByCusQy(cusCountDto);
			}
			// 认筹
			if (heroCount_rc.size() > 0) {
				for (int i = 0; i < heroCount_rc.size(); i++) {
					GroupHeroListRes groupHero_rc = new GroupHeroListRes();
					groupHero_rc.setGroupName(heroCount_rc.get(i).getGroupName());// 销售组名称
					groupHero_rc.setCusTypeName(heroCount_rc.get(i).getCusTypeName());// 类型名称
					if ("1".equals(reqDto.getCusType())) {
						groupHero_rc.setCusNum(heroCount_rc.get(i).getCusNum());// 成绩数量
					} else {
						if (heroCount_rc.get(i).getCusAmount() != null && !"".equals(heroCount_rc.get(i).getCusAmount())) {
							groupHero_rc.setCusAmount(df.format(Double.valueOf(heroCount_rc.get(i).getCusAmount()) / 10000));// 金额
						} else {
							groupHero_rc.setCusAmount("0");
						}
					}
					// 排名
					if (i == 0) {
						groupHero_rc.setRanking("冠军");
					} else if (i == 1) {
						groupHero_rc.setRanking("亚军");
					} else if (i == 2) {
						groupHero_rc.setRanking("季军");
					}
					groupHeroList.add(groupHero_rc);
				}
				resDto.setGroupHeroList(groupHeroList);
			} else {
				resDto.setGroupHeroList(null);
			}
			// 认购
			if (heroCount_rg.size() > 0) {
				for (int i = 0; i < heroCount_rg.size(); i++) {
					GroupHeroSubListRes groupHero_rg = new GroupHeroSubListRes();
					groupHero_rg.setGroupName_sub(heroCount_rg.get(i).getGroupName());// 销售组名称
					groupHero_rg.setCusTypeName_sub(heroCount_rg.get(i).getCusTypeName());// 类型名称
					if ("1".equals(reqDto.getCusType())) {
						groupHero_rg.setCusNum_sub(heroCount_rg.get(i).getCusNum());// 成绩数量
					} else {
						if (heroCount_rg.get(i).getCusAmount() != null && !"".equals(heroCount_rg.get(i).getCusAmount())) {
							groupHero_rg.setCusAmount_sub(df.format(Double.valueOf(heroCount_rg.get(i).getCusAmount()) / 10000));// 金额
						} else {
							groupHero_rg.setCusAmount_sub("0");
						}
					}
					// 排名
					if (i == 0) {
						groupHero_rg.setRanking_sub("冠军");
					} else if (i == 1) {
						groupHero_rg.setRanking_sub("亚军");
					} else if (i == 2) {
						groupHero_rg.setRanking_sub("季军");
					}
					groupHeroSubList.add(groupHero_rg);
				}
				resDto.setGroupHeroSubList(groupHeroSubList);
			} else {
				resDto.setGroupHeroSubList(null);
			}
			// 签约
			if (heroCount_qy.size() > 0) {
				for (int i = 0; i < heroCount_qy.size(); i++) {
					GroupHeroSignedListRes groupHero_qy = new GroupHeroSignedListRes();
					groupHero_qy.setGroupName_sig(heroCount_qy.get(i).getGroupName());// 销售组名称
					groupHero_qy.setCusTypeName_sig(heroCount_qy.get(i).getCusTypeName());// 类型名称
					if ("1".equals(reqDto.getCusType())) {
						groupHero_qy.setCusNum_sig(heroCount_qy.get(i).getCusNum());// 成绩数量
					} else {
						if (heroCount_qy.get(i).getCusAmount() != null && !"".equals(heroCount_qy.get(i).getCusAmount())) {
							groupHero_qy.setCusAmount_sig(df.format(Double.valueOf(heroCount_qy.get(i).getCusAmount()) / 10000));// 金额
						} else {
							groupHero_qy.setCusAmount_sig("0");
						}
					}
					// 排名
					if (i == 0) {
						groupHero_qy.setRanking_sig("冠军");
					} else if (i == 1) {
						groupHero_qy.setRanking_sig("亚军");
					} else if (i == 2) {
						groupHero_qy.setRanking_sig("季军");
					}
					groupHeroSignedList.add(groupHero_qy);
				}
				resDto.setGroupHeroSignedList(groupHeroSignedList);
			} else {
				resDto.setGroupHeroSignedList(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("查询销售组英雄榜信息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * getNextReminderList:(app查询下次跟进提醒列表接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param pageNumber
	 *            页码
	 * @param pageSize
	 *            页码大小
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetNextReminderListResDto getNextReminderList(
			GetNextReminderListReqDto reqDto) {
		GetNextReminderListResDto resDto = new GetNextReminderListResDto();
		List<NextReminderListRes> nextReminderList = new ArrayList<NextReminderListRes>();
		String pageNumber = reqDto.getPageNumber();// 页码
		String pageSize = reqDto.getPageSize();// 页码大小
		try {
			FollowDto entity = new FollowDto();
			entity.setMerchantId(reqDto.getMerchantId());
			entity.setProjectCode(reqDto.getProjectCode());
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			entity.setUserCode(user.getUserCode());
			entity.setIsSend(IsSendEnum.SEND.getNo());
			entity.setOrders("  t.next_follow_time desc ");
			Page<Follow> followPage = followService.getPageModel(entity,PageUtil.begin(Integer.parseInt(pageNumber),Integer.parseInt(pageSize)),Integer.parseInt(pageSize));
			if(followPage.getRows().size() > 0 ){
				List<Follow> followList = followPage.getRows();
				for(Follow follow : followList){
					NextReminderListRes nextReminderListRes = new NextReminderListRes();
					nextReminderListRes.setNextRemindContent(follow.getNextFollowContent());
					nextReminderListRes.setNextReminderDate(sdf_follow.format(follow.getNextFollowTime()));
					nextReminderListRes.setIsRead(follow.getIsRead());
					nextReminderList.add(nextReminderListRes);

					//更新下次提醒是否已读标识：为已读
					FollowDto followDto = new FollowDto();
					followDto.setId(follow.getId());
					followDto.setIsRead(IsReadEnum.READ.getNo());
					followDto.setUpdateUserId(Long.valueOf(reqDto.getUserId()));
					followDto.setUpdateTime(new Date());
					followService.update(followDto);
				}
				resDto.setTotalPage(String.valueOf(followPage.getTotalPages()));
				resDto.setTotalCount(String.valueOf(followPage.getTotal()));
				resDto.setNextReminderList(nextReminderList);
			}else{
				resDto.setTotalPage("0");
				resDto.setTotalCount("0");
				resDto.setNextReminderList(null);
			}
		} catch (Exception e) {
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("查询下次跟进提醒列表失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
		}
		resDto.setPageNumber(pageNumber);
		resDto.setPageSize(pageSize);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 新增客户签约推送push消息
	 *
	 * @param signedDto 签约记录
	 * @return
	 */
	public CommonResDTO addSignedNotice(SignedDto signedDto, String flag){
		CommonResDTO resDto = new CommonResDTO();
		try {
			//待审核数据,发送消息
			if(AuditStatusEnum.AUDIT.getNo().equals(signedDto.getAuditStatus())){
				//客户
				String cusName = "";
				Customer customer = customerService.selectById(signedDto.getCustomerId());
				if(customer != null){
					cusName = customer.getCustomerName();
				}

				/**
				 * 消息接收人
				 * 1、根据审批节点人员确定
				 */
				//获取当前项目下审批节点人map
				ProjectSettingDto pDto = new ProjectSettingDto();
				pDto.setProjectCode(signedDto.getProjectCode());
				ProjectSetting pObj = projectSettingService.selectByDto(pDto);
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("projectApprovalUser", pObj.getProjectLeader());
				variables.put("marketingApprovalUser", pObj.getSaleLeader());
				variables.put("caseApprovalUser", pObj.getFieldLeader());
				variables.put("financeApprovalUser", pObj.getFinanceLeader());
				variables.put("saleManagerApprovalUser", pObj.getMaLeader());

				//获取审批人userId
				List<User> userList = new ArrayList<User>();
				ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(signedDto.getProcInstId()).singleResult();
				BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
				if(model != null) {
					Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
					for(FlowElement e : flowElements) {
						if(e instanceof UserTask){
							List<String> userIds = activitiProcessService.getNodeUserId(signedDto.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
							for(String userId : userIds){
								User user = new User();
								user.setId(Long.valueOf(userId));
								userList.add(user);
							}
						}
					}
				}

				//项目
				/*String proName = "";
				Project project = null;
				if(signedDto.getProjectId() != null){
					project = projectService.selectById(signedDto.getProjectId());
					if(project != null){
						proName = project.getProjectName();
					}
				}*/

				//获取归属人
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				User userAgent_gsr = userService.selectByDto(userDto);

				/*String pushType = "SHSQ";*/

				//获取经纪人
				/*String userName = "";
				TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
				transactionRelationDto.setBusinessId(signedDto.getId());
				List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
				if(transactionRelationList.size() > 0){
					for(int i=0;i< transactionRelationList.size() ;i++){
						User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
						if(user.getUserName() != null && !"".equals(user.getUserName())){
							if(transactionRelationList.size() == 1){
								userName = user.getUserName();
							}else{
								userName += "；经纪人"+(i+1)+"："+user.getUserName();
							}
						}
					}
				}*/

				//签约折扣, 获取字典表dictionary_value = 'NT10' 的消息模板
				//消息模板: 签约折扣：购房折扣审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				if(flag == "1"){
					String msgTemp = "购房折扣审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT10");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(signedDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId", "173");
					noticeParamMap.put("noticeTempType", "NT10");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "签约折扣审批申请");
					noticeParamMap.put("merchantId", String.valueOf(signedDto.getMerchantId()));
					noticeParamMap.put("projectCode", signedDto.getProjectCode());
					noticeParamMap.put("userCode", signedDto.getUserCode());
					noticeParamMap.put("accessCode", signedDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(signedDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "签约折扣提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);

					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT10","签约折扣审批申请", flag);
					}

				//签约, 获取字典表dictionary_value = 'NT09' 的消息模板
				//消息模板: 签约：签约审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				}else if(flag == "2"){
					String msgTemp = "签约审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT09");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(signedDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId", "172");
					noticeParamMap.put("noticeTempType", "NT09");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "签约审批申请");
					noticeParamMap.put("merchantId", String.valueOf(signedDto.getMerchantId()));
					noticeParamMap.put("projectCode", signedDto.getProjectCode());
					noticeParamMap.put("userCode", signedDto.getUserCode());
					noticeParamMap.put("accessCode", signedDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(signedDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "签约提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);

					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT09","签约审批申请", flag);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增签约消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 修改客户签约推送push消息
	 *
	 * @param signedDto 签约记录
	 * @return
	 */
	public CommonResDTO editSignedNotice(Signed signed, String flag){
		CommonResDTO resDto = new CommonResDTO();
		try {
			//待审核数据,发送消息
			if(AuditStatusEnum.AUDIT.getNo().equals(signed.getAuditStatus())){
				//客户
				String cusName = "";
				Customer customer = customerService.selectById(signed.getCustomerId());
				if(customer != null){
					cusName = customer.getCustomerName();
				}

				/**
				 * 消息接收人
				 * 1、根据审批节点人员确定
				 */
				//获取当前项目下审批节点人map
				ProjectSettingDto pDto = new ProjectSettingDto();
				pDto.setProjectCode(signed.getProjectCode());
				ProjectSetting pObj = projectSettingService.selectByDto(pDto);
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("projectApprovalUser", pObj.getProjectLeader());
				variables.put("marketingApprovalUser", pObj.getSaleLeader());
				variables.put("caseApprovalUser", pObj.getFieldLeader());
				variables.put("financeApprovalUser", pObj.getFinanceLeader());
				variables.put("saleManagerApprovalUser", pObj.getMaLeader());

				//获取审批人userId
				List<User> userList = new ArrayList<User>();
				HistoricProcessInstance historicProcessInstance = null;
				if("1".equals(signed.getDiscountApproval())){
					BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
					businessAbnormaDto.setBusinessId(signed.getId());
					businessAbnormaDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
					businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					List<BusinessAbnorma> businessAbnormaList = businessAbnormaService.selectListByDto(businessAbnormaDto);
					if(businessAbnormaList.size() > 0 && businessAbnormaList != null){
						historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(businessAbnormaList.get(0).getProcInstId()).singleResult();
					}else{
						BusinessAbnormaDto baDto = new BusinessAbnormaDto();
						baDto.setBusinessId(signed.getId());//业务ID
						List<BusinessAbnorma> baList = businessAbnormaService.selectListByDto(baDto);
						if(baList.size() > 0){
							for(BusinessAbnorma baEntity : baList){
								if("3".equals(baEntity.getAuditStatus())){
									historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(signed.getProcInstId()).singleResult();
								}
							}
						}
					}
				}else{
					historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(signed.getProcInstId()).singleResult();
				}
//				ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(signed.getProcInstId()).singleResult();
				BpmnModel model = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
				if(model != null) {
					Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
					for(FlowElement e : flowElements) {
						if(e instanceof UserTask){
							List<String> userIds = activitiProcessService.getNodeUserId(signed.getMerchantId(),null,historicProcessInstance.getProcessDefinitionId(),e.getId());
							for(String userId : userIds){
								User user = new User();
								user.setId(Long.valueOf(userId));
								userList.add(user);
							}
						}
					}
				}

				//项目
				/*String proName = "";
				Project project = null;
				if(signed.getProjectId() != null){
					project = projectService.selectById(signed.getProjectId());
					if(project != null){
						proName = project.getProjectName();
					}
				}*/

				//获取归属人
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				User userAgent_gsr = userService.selectByDto(userDto);

				/*String pushType = "SHSQ";*/

				//获取经纪人
				/*String userName = null;
				TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
				transactionRelationDto.setBusinessId(signed.getId());
				List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
				if(transactionRelationList.size() > 0){
					for(int i=0;i< transactionRelationList.size() ;i++){
						User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
						if(user.getUserName() != null){
							if(transactionRelationList.size() == 1){
								userName = user.getUserName();
							}else{
								userName += "；经纪人"+i+1+"："+user.getUserName();
							}
						}
					}
				}*/

				//签约折扣, 获取字典表dictionary_value = 'NT10' 的消息模板
				//消息模板: 签约折扣：购房折扣审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				if(flag == "1"){
					String msgTemp = "购房折扣审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT10");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(signed.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId", "173");
					noticeParamMap.put("noticeTempType", "NT10");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "签约折扣审批申请");
					noticeParamMap.put("merchantId", String.valueOf(signed.getMerchantId()));
					noticeParamMap.put("projectCode", signed.getProjectCode());
					noticeParamMap.put("userCode", signed.getUserCode());
					noticeParamMap.put("accessCode", signed.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(signed.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "签约折扣提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);

					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT10","签约折扣审批申请", flag);
					}

				//签约, 获取字典表dictionary_value = 'NT09' 的消息模板
				//消息模板: 签约：签约审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				}else if(flag == "2"){
					String msgTemp = "签约审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT09");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(signed.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId", "172");
					noticeParamMap.put("noticeTempType", "NT09");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "签约审批申请");
					noticeParamMap.put("merchantId", String.valueOf(signed.getMerchantId()));
					noticeParamMap.put("projectCode", signed.getProjectCode());
					noticeParamMap.put("userCode", signed.getUserCode());
					noticeParamMap.put("accessCode", signed.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(signed.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "签约提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);

					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT09","签约审批申请", flag);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增签约消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	public void pushMsg(String projectCode,String projectName,String noticeTempType,String actionTitle, String flag) throws Exception{
		//1、查询认筹审核申请相关推送消息
		// NT07: 认筹审核申请
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
 		int year = calendar.get(Calendar.YEAR);
 		int month = calendar.get(Calendar.MONTH) + 1;
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
// 		String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00";
 		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59";
 		MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
 		withHouseMrDto.setNoticeTempType(noticeTempType);
 		withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
 		//loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
 		withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
   	 	if(withHouseMrList != null){
   	 		for(MessageReceiverDto withHouseMr: withHouseMrList){
   	 			msgRecList.add(withHouseMr);
   	 		}
   	 	}

   	 	if(msgRecList != null && msgRecList.size() > 0){
   	 		String noticeIds = "";
   	 		String msgRecIds = "";
   	 		Set<String> noticeIdSet = new HashSet<String>();
   	 		for(MessageReceiverDto msgRecDto: msgRecList){
   	 			//开始推送消息
	   	 		Map<String, String> pushMap = new HashMap<String, String>();
	   	 		if(flag == "1"){
	   	 			pushMap.put("action", "签约折扣提交审核提醒");
	   	 		}else{
	   	 			pushMap.put("action", "签约提交审核提醒");
	   	 		}
		   	 	pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
//		   	 	pushMap.put("pushType", msgRecDto.getNoticeTempType());
		   	 	pushMap.put("pushType", "SHSQ");
		   	    pushMap.put("projectCode",projectCode);
		   	    pushMap.put("projectName", projectName);
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context,
					msgRecDto.getTitle(), pushMap);

				//消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				//消息接收人ID'S
				if(StringUtils.isNotEmpty(msgRecIds)){
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
   	 		}
   	 		//需更新消息ID'S
   	 		if(!noticeIdSet.isEmpty()){
				for(String noticeId: noticeIdSet){
					if(StringUtils.isNotEmpty(noticeIds)){
						noticeIds += ",";
					}
					noticeIds += noticeId;
	   	 		}
   	 		}
   	 		//更新消息
   	 		NoticeDto noticeDto = new NoticeDto();
   	 		noticeDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		noticeService.updates(noticeDto, noticeIds);
   	 		//更新接收人
   	 		MessageReceiverDto updateMRDto = new MessageReceiverDto();
   	 		updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		messageReceiverService.updates(updateMRDto, msgRecIds);
   	 	}
	}

	/**
	 * getSignedHaveAmount:(app查询签约已收金额接口) - serviceImpl
	 *
	 * @author 作者(ny)
	 * @param version
	 *            app版本号
	 * @param merchantId
	 *            商户Id
	 * @param userId
	 *            用户编号
	 * @param token
	 *            会话token
	 * @param projectCode
	 *            项目code
	 * @param businessId
	 *            业务Id：认筹、认购、签约Id
	 * @param businessType
	 *            业务类型：1、认筹转签约；2、认购转签约；3、新增签约（业务Id可为空）；4、修改签约；5 查看签约详情
	 * @param terminalCode
	 *            终端编码
	 * @return
	 */
	@Override
	public GetSignedHaveAmountResDto getSignedHaveAmount(
			GetSignedHaveAmountReqDto reqDto) {
		GetSignedHaveAmountResDto resDto = new GetSignedHaveAmountResDto();
		try{
			HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
			if(!"3".equals(reqDto.getBusinessType())){
				entity.setRelationId(Long.valueOf(reqDto.getBusinessId()));
			}
			entity.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
			entity.setDocType(DocTypeEnum.COLLECTION.getNo());
			Signed signed = null;
			if("0".equals(reqDto.getBusinessType())){
				entity.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
			}else if("1".equals(reqDto.getBusinessType())){
				entity.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
			}else if("4".equals(reqDto.getBusinessType())){
				signed = signedService.selectById(Long.valueOf(reqDto.getBusinessId()));
				if(signed != null){
					if(signed.getSubscribeId() != null && !"".equals(signed.getSubscribeId())){
						entity.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
					}else{
						if(signed.getPayDepositId() != null && !"".equals(signed.getPayDepositId())){
							entity.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
						}
					}
				}
			}else if("5".equals(reqDto.getBusinessType())){
				entity.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
			}
			//add 2016-12-07 author ny
			entity.setAccessCode(reqDto.getProjectCode());
			Double realAmount = haveReceiveRefundService.haveReceiveAmount(entity);
			if("3".equals(reqDto.getBusinessType())){
				resDto.setRealAmount("0");
			}else if("4".equals(reqDto.getBusinessType())){
				if(signed != null){
					if(signed.getSubscribeId() != null || signed.getPayDepositId() != null){
						resDto.setRealAmount(String.valueOf(realAmount));
					}else{
						resDto.setRealAmount("0");
					}
				}
			}else{
				resDto.setRealAmount(String.valueOf(realAmount));
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("查询签约已收金额失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	@SuppressWarnings("unused")
	private void conversionHaveReceive(Signed signed,List<NeedReceiveRefund> needList){
		List<HaveReceiveRefund> convertList=new ArrayList<HaveReceiveRefund>();
		//查询认筹已收
		//查询认购已收
		//绑定签约应收第一条
		if(signed.getSubscribeId()!=null){
			Subscribe subscribe=subscribeService.selectById(signed.getSubscribeId());
			//认购转签约
			HaveReceiveRefundDto haveReceiveRefundDto=new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(subscribe.getId());
			//已收
			haveReceiveRefundDto.setDocType("0");
			//认购
			haveReceiveRefundDto.setReceivablesType("1");
			//正常
			haveReceiveRefundDto.setTransferStatus("0");
			List<HaveReceiveRefund> haveReceiveList = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
			if(null!=haveReceiveList && haveReceiveList.size()>0){
				for (HaveReceiveRefund have:haveReceiveList) {
					if(!have.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())){
						convertList.add(have);
					}
				}
			}
		}else if(signed.getPayDepositId()!=null){
			//认筹转认购
			HaveReceiveRefundDto haveReceiveRefundDto=new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(signed.getPayDepositId());
			//已收
			haveReceiveRefundDto.setDocType("0");
			//认筹
			haveReceiveRefundDto.setReceivablesType("0");
			List<HaveReceiveRefund> haveReceiveList = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
			if(null!=haveReceiveList && haveReceiveList.size()>0){
				for (HaveReceiveRefund have:haveReceiveList) {
					if(!have.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())){
						convertList.add(have);
					}
				}

			}
		}

		//查找应收
		NeedReceiveRefund tempNeedReceive=null;
		for(NeedReceiveRefund nrr : needList){
			String housingFundTyp=nrr.getHousingFundType();
			if(housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_5.getNo()) ||
			   housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo()) ||
			   housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo()) ||
			   housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_12.getNo()) ||
			   housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo()) ){
				tempNeedReceive=nrr;
				break;
			}
		}
		if(null!=tempNeedReceive){
			for(HaveReceiveRefund hrr : convertList){
				try {
					//原记录更新为转出
					HaveReceiveRefundDto updateDto=new HaveReceiveRefundDto();
					updateDto.setId(hrr.getId());
					updateDto.setTransferStatus("1");
					haveReceiveRefundService.update(updateDto);
					//转到应收下
					HaveReceiveRefundDto haveReceiveRefundDto=new HaveReceiveRefundDto();
					haveReceiveRefundDto=BeanUtil.convert2T(haveReceiveRefundDto, hrr);
					haveReceiveRefundDto.setId(null);
					haveReceiveRefundDto.setRelationId(signed.getId());
					haveReceiveRefundDto.setReceivablesType("2");
					haveReceiveRefundDto.setReceivablesId(tempNeedReceive.getId());
					haveReceiveRefundDto.setHousingFundType(tempNeedReceive.getHousingFundType());
					haveReceiveRefundDto.setBusinessFlag(tempNeedReceive.getBusinessFlag());
					haveReceiveRefundDto.setCreateTime(new Date());
					haveReceiveRefundService.create(haveReceiveRefundDto);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}

	}

	@Override
	public GetRecommendCustomerListResDto getRecommendCustomerList(
			GetRecommendCustomerListReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、查询客户推荐人
		return getRecommendCustomerListManage.getRecommendCustomerList(reqDto);
	}

	/**
	 * 更新客户跟进
	 * */
	@Override
	public EditFollowResDto editFollow(EditFollowReqDto reqDto) {
		EditFollowResDto resDto = new EditFollowResDto();
		try{
			FollowDto followDto = new FollowDto();
			followDto.setId(Long.valueOf(reqDto.getFollowId()));
			followDto.setFollowTime(Calendar.getInstance().getTime());
			followDto.setFollowContent(SysConstants.OUTGONING_NOT_CONNECTED);
			followDto.setFollowType(FollowTypeEnum.TEXT.getNo());
			followService.update(followDto);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("更新客户跟进失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 查询用户电话列表
	 * */
	@Override
	public GetUserCallListResDto getUserCallList(GetUserCallListReqDto reqDto) {
		GetUserCallListResDto resDto = new GetUserCallListResDto();
		List<UserCallListRes> userCallList = new ArrayList<UserCallListRes>();
		try{
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			if(user != null){
				/**
				 * 查询该用户所属商户是否已开通电话平台
				 * 是否已开通电话平台：0、未开通；1、已开通
				 */
				Merchant merchant = merchantService.selectById(Long.valueOf(reqDto.getMerchantId()));
				if(merchant.getPhoneInformation() != null && !"".equals(merchant.getPhoneInformation())){
					String isPhoneInformation = merchant.getPhoneInformation();
					JSONArray jsonArray=JSON.parseArray(isPhoneInformation);
					for(int i=0;i<jsonArray.size();i++){
						JSONObject row=jsonArray.getJSONObject(i);
						if("1".equals(row.getString("type"))){//type类型等于“1”代表电话平台
							resDto.setIsPhoneInformation(row.getString("status"));
						}
					}
				}else{
					resDto.setIsPhoneInformation("0");
				}

				UserCallListRes userCallRes = new UserCallListRes();
				userCallRes.setTelePhoneType("1");
				userCallRes.setTelePhone(user.getUserPhone());
				userCallList.add(userCallRes);

				String userLandlines=user.getUserLandlines();
	    		if(StringUtils.isNotBlank(userLandlines)){
	    			JSONArray phoneArray=JSON.parseArray(userLandlines);
	    			for(int i=0;i<phoneArray.size();i++){
	    				UserCallListRes userCallResTwo = new UserCallListRes();
	    				JSONObject row=phoneArray.getJSONObject(i);
	    				String rowPhone=row.getString("phone");
	    				String rowType=row.getString("type");
	    				if(StringUtils.isBlank(rowPhone) && StringUtils.isBlank(rowType))continue;
	    				userCallResTwo.setTelePhoneType(rowType);
	    				userCallResTwo.setTelePhone(rowPhone);
	    				userCallList.add(userCallResTwo);
	    			}
	    		}
	    		resDto.setUserCallList(userCallList);
			}else{
				resDto.setUserCallList(null);
			}
			 resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("查询用户电话列表失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 拨打电话并初始化生成跟进记录
	 * */
	@Override
	public GetCallBackResDto getCallBack(GetCallBackReqDto reqDto) {
		GetCallBackResDto resDto = new GetCallBackResDto();
		try{
			TelRecordDto trd = new TelRecordDto();
			trd.setMerchantId(reqDto.getMerchantId());//商户ID
			trd.setProjectId(reqDto.getProjectId());//项目ID
			trd.setCreateUserId(Long.valueOf(reqDto.getUserId()));//用户ID
			trd.setCaller(reqDto.getCaller());//主叫号码
			trd.setCalled(reqDto.getCalled());//被叫号码
			trd.setCallType("0");//通话类型:0：呼出；1：呼入
			trd.setTerminalType("1");//终端类型:0：PC；1：手机；3:座机
			trd.setTerminalModel(reqDto.getTerminalModel());//终端操作模块:0：客户；
			trd.setTerminalModelId(Long.valueOf(reqDto.getTerminalModelId()));
			//查询用户信息
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			trd.setUserCode(user.getUserCode());//用户code
			trd.setAccessCode(reqDto.getProjectCode());//项目编码

			FollowDto fd = new FollowDto();
			fd.setCustomerId(Long.valueOf(reqDto.getCustomerId()));//客户ID
			fd.setMerchantId(reqDto.getMerchantId());//商户ID
			fd.setProjectId(reqDto.getProjectId());//项目ID
			fd.setProjectCode(reqDto.getProjectCode());//项目编码
			fd.setUserCode(user.getUserCode());//用户code
			fd.setAccessCode(reqDto.getProjectCode());//项目编码
			fd.setCreateUserId(Long.valueOf(reqDto.getUserId()));//用户ID
			FollowDto followDto = dialTransactionalService.callAndFollow(trd, fd);
			if(followDto != null){
				resDto.setFollowId(String.valueOf(followDto.getId()));
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("拨打电话失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 *
	 * （1）项目信息全量查询接口(queryProjectInfo)
	 * @author Administrator
	 *
	 */
	@Override
	public QueryProjectInfoResDto queryProjectInfo(QueryProjectInfoReqDto reqDto) {
		QueryProjectInfoResDto resDto = new QueryProjectInfoResDto();
		List<ProjectInfoListRes> projectInfoList = new ArrayList<ProjectInfoListRes>();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			MerchantDto entity = new MerchantDto();
			entity.setMerchantCode(reqDto.getToken());
			Merchant merchant = merchantService.selectByDto(entity);
			if(merchant != null){
				ProjectDto proEntity = new ProjectDto();
				proEntity.setMerchantId(merchant.getId());
				List<Project> projectList = projectService.selectListByDto(proEntity);
				if(projectList.size() > 0){
					for(Project pro : projectList){
						ProjectInfoListRes projectInfoRes = new ProjectInfoListRes();
						projectInfoRes.setProjectCode(pro.getProjectCode());//项目code
						projectInfoRes.setProjectName(pro.getProjectName());//项目名称
						//分期数
						if(pro.getStagesNum() != null && !"".equals(pro.getStagesNum())){
							projectInfoRes.setStagesNum(String.valueOf(pro.getStagesNum()));
						}else{
							projectInfoRes.setStagesNum(null);//分期数
						}
						//所在省份
						if(pro.getProvinceId() != null && !"".equals(pro.getProvinceId())){
							Area area_pro = areaService.selectById(pro.getProvinceId());
							if(area_pro != null){
								projectInfoRes.setProvinceName(area_pro.getAreaName());
							}else{
								projectInfoRes.setProvinceName(null);
							}
						}else{
							projectInfoRes.setProvinceName(null);
						}
						//所在城市
						if(pro.getCityId() != null && !"".equals(pro.getCityId())){
							Area area_city = areaService.selectById(pro.getCityId());
							if(area_city != null){
								projectInfoRes.setCityName(area_city.getAreaName());
							}else{
								projectInfoRes.setCityName(null);
							}
						}else{
							projectInfoRes.setCityName(null);
						}
						//所在区
						if(pro.getAreaId() != null && !"".equals(pro.getAreaId())){
							Area area = areaService.selectById(pro.getAreaId());
							if(area != null){
								projectInfoRes.setAreaName(area.getAreaName());
							}else{
								projectInfoRes.setAreaName(null);
							}
						}else{
							projectInfoRes.setAreaName(null);
						}
						//产品类型
						if(pro.getProjectType() != null && !"".equals(pro.getProjectType())){
							String projectType = pro.getProjectType();
							String s[] = projectType.split(",");
							String n = "";
							for(int i=0;i<s.length;i++){
								n += ProjectTypeEnum.getByNo(s[i]).getDes()+",";
							}
							String typeName = n.substring(0,n.length()-1);
							projectInfoRes.setProjectType(typeName);
						}else{
							projectInfoRes.setProjectType(null);
						}
						//容积率
						if(pro.getPlotRatio() != null && !"".equals(pro.getPlotRatio())){
							projectInfoRes.setPlotRatio(String.valueOf(pro.getPlotRatio()));
						}else{
							projectInfoRes.setPlotRatio(null);
						}
						//绿化率
						if(pro.getGreeningRate() != null && !"".equals(pro.getGreeningRate())){
							projectInfoRes.setGreeningRate(String.valueOf(pro.getGreeningRate()));
						}else{
							projectInfoRes.setGreeningRate(null);
						}
						//占地面积
						if(pro.getFloorSpace() != null && !"".equals(pro.getFloorSpace())){
							projectInfoRes.setFloorSpace(String.valueOf(pro.getFloorSpace()));
						}else{
							projectInfoRes.setFloorSpace(null);
						}
						//总户数
						if(pro.getHouseholdsTotal() != null && !"".equals(pro.getHouseholdsTotal())){
							projectInfoRes.setHouseholdsTotal(String.valueOf(pro.getHouseholdsTotal()));
						}else{
							projectInfoRes.setHouseholdsTotal(null);
						}
						//车位数
						if(pro.getCarportTotal() != null && !"".equals(pro.getCarportTotal())){
							projectInfoRes.setCarportTotal(String.valueOf(pro.getCarportTotal()));
						}else{
							projectInfoRes.setCarportTotal(null);
						}
						//车位配比
						if(pro.getCarportMatching() != null && !"".equals(pro.getCarportMatching())){
							projectInfoRes.setCarportMatching(pro.getCarportMatching());
						}else{
							projectInfoRes.setCarportMatching(null);
						}
						//销售热线
						if(pro.getSalesHotline() != null && !"".equals(pro.getSalesHotline())){
							projectInfoRes.setSalesHotline(pro.getSalesHotline());
						}else{
							projectInfoRes.setSalesHotline(null);
						}
						//售楼地址
						if(pro.getSalesAddress() != null && !" ".equals(pro.getSalesAddress())){
							projectInfoRes.setSalesAddress(pro.getSalesAddress());
						}else{
							projectInfoRes.setSalesAddress(null);
						}
						//物业公司
						if(pro.getPropertyCompany() != null && !"".equals(pro.getPropertyCompany())){
							projectInfoRes.setPropertyCompany(pro.getPropertyCompany());
						}else{
							projectInfoRes.setPropertyCompany(null);
						}
						//开发商名称
						if(pro.getDeveloperName() != null && !"".equals(pro.getDeveloperName())){
							projectInfoRes.setDeveloperName(pro.getDeveloperName());
						}else{
							projectInfoRes.setDeveloperName(null);
						}
						//开发商地址
						if(pro.getDeveloperAddress() != null && !"  ".equals(pro.getDeveloperAddress())){
							projectInfoRes.setDeveloperAddress(pro.getDeveloperAddress());
						}else{
							projectInfoRes.setDeveloperAddress(null);
						}
						//楼盘地址
						if(pro.getPremisesAddress() != null && !"  ".equals(pro.getPremisesAddress())){
							projectInfoRes.setPremisesAddress(pro.getPremisesAddress());
						}else{
							projectInfoRes.setPremisesAddress(null);
						}
						//产权年限
						if(pro.getPropertyYear() != null && !"".equals(pro.getPropertyYear())){
							projectInfoRes.setPropertyYear(String.valueOf(pro.getPropertyYear()));
						}else{
							projectInfoRes.setPropertyYear(null);
						}
						//建造进度
						if(pro.getBuildingSchedule() != null && !"".equals(pro.getBuildingSchedule())){
							projectInfoRes.setBuildingSchedule(pro.getBuildingSchedule());
						}else{
							projectInfoRes.setBuildingSchedule(null);
						}
						//开工时间
						if(pro.getStartTime() != null){
							projectInfoRes.setStartTime(sdf.format(pro.getStartTime()));
						}else{
							projectInfoRes.setStartTime(null);
						}
						//交付情况
						if(pro.getDeliveryStatus() != null && !"".equals(pro.getDeliveryStatus())){
							projectInfoRes.setDeliveryStatus(DeliveryStatusEnum.getByNo(pro.getDeliveryStatus()).getDes());
						}else{
							projectInfoRes.setDeliveryStatus(null);
						}
						//交付日期
						if(pro.getDeliveryDate() != null){
							projectInfoRes.setDeliveryDate(sdf.format(pro.getDeliveryDate()));
						}else{
							projectInfoRes.setDeliveryDate(null);
						}
						//销售情况
						if(pro.getSalesStatus() != null && !"".equals(pro.getSalesStatus())){
							projectInfoRes.setSalesStatus(SalesStatusEnum.getByNo(pro.getSalesStatus()).getDes());
						}else{
							projectInfoRes.setSalesStatus(null);
						}
						//预售证编号
						if(pro.getSalesPermissionNo() != null && !"null".equals(pro.getSalesPermissionNo())){
							projectInfoRes.setSalesPermissionNo(pro.getSalesPermissionNo());
						}else{
							projectInfoRes.setSalesPermissionNo(null);
						}
						//预售证领取日期
						if(pro.getSalesPermissionDate() != null){
							projectInfoRes.setSalesPermissionDate(sdf.format(pro.getSalesPermissionDate()));
						}else{
							projectInfoRes.setSalesPermissionDate(null);
						}
						//楼盘概况
						if(pro.getPremisesCase() != null && !" ".equals(pro.getPremisesCase())){
							projectInfoRes.setPremisesCase(pro.getPremisesCase());
						}else{
							projectInfoRes.setPremisesCase(null);
						}
						//项目配套
						if(pro.getProjectRequirement() != null && !"  ".equals(pro.getProjectRequirement())){
							projectInfoRes.setProjectRequirement(pro.getProjectRequirement());
						}else{
							projectInfoRes.setProjectRequirement(null);
						}
						//交通情况
						if(pro.getTrafficCase() != null && !"  ".equals(pro.getTrafficCase())){
							projectInfoRes.setTrafficCase(pro.getTrafficCase());
						}else{
							projectInfoRes.setTrafficCase(null);
						}
						projectInfoList.add(projectInfoRes);
					}
					resDto.setProjectInfoList(projectInfoList);
				}else{
					resDto.setProjectInfoList(null);
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("项目信息全量查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 *
	 * （2）经纪人信息全量查询接口(queryAgentInfo)
	 * @author Administrator
	 *
	 */
	@Override
	public QueryAgentInfoResDto queryAgentInfo(QueryAgentInfoReqDto reqDto) {
		QueryAgentInfoResDto resDto = new QueryAgentInfoResDto();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			List<AgentInfoListRes> userList = queryAllUser(reqDto.getToken());
			if(userList.size() > 0){
				resDto.setAgentInfoList(userList);
			}else{
				resDto.setAgentInfoList(null);
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("经纪人信息全量查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 *
	 * （3）经纪人与项目的归属关系全量查询接口(queryProjectRelationAgentInfo)
	 * @author Administrator
	 *
	 */
	@Override
	public QueryProjectRelationAgentInfoResDto queryProjectRelationAgentInfo(
			QueryProjectRelationAgentInfoReqDto reqDto) {
		QueryProjectRelationAgentInfoResDto resDto = new QueryProjectRelationAgentInfoResDto();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			List<AgentInfoListRes> userList = queryUserList(reqDto.getToken(), reqDto.getProjectCode());
			if(userList.size() > 0){
				resDto.setAgentInfoList(userList);
			}else{
				resDto.setAgentInfoList(null);
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("经纪人与项目的归属关系全量查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	public List<AgentInfoListRes> queryAllUser(String merchantCode){
		List<AgentInfoListRes> agentInfoList = new ArrayList<AgentInfoListRes>();
		MerchantDto entity = new MerchantDto();
		entity.setMerchantCode(merchantCode);
		Merchant merchant = merchantService.selectByDto(entity);
		if(merchant != null){
			UserDto query=new UserDto();
			query.setMerchantId(merchant.getId());
			query.setIsAdmin("0");
			List<User> userList=userService.selectListByDto(query);
			if(null!=userList){
				for(User user : userList){
					AgentInfoListRes agentInfoListRes = new AgentInfoListRes();
					agentInfoListRes.setUserName(user.getUserName());//姓名
					agentInfoListRes.setMobile(user.getUserPhone());//手机号码
					//生日
					if(user.getBirthday() != null){
						agentInfoListRes.setBirthday(sdf.format(user.getBirthday()));
					}else{
						agentInfoListRes.setBirthday(null);
					}
					//入职时间
					if(user.getEntryTime() != null){
						agentInfoListRes.setEntryTime(sdf.format(user.getEntryTime()));
					}else{
						agentInfoListRes.setEntryTime(null);
					}
					//头像
					if(user.getHeadPic() != null){
						agentInfoListRes.setHeadPic(user.getHeadPic());
					}else{
						agentInfoListRes.setHeadPic(null);
					}
					//所属部门
					if(user.getUserDepartmentId() != null){
						Department department = departmentService.selectById(user.getUserDepartmentId());
						if(department != null){
							agentInfoListRes.setUserDepartmentName(department.getDepartmentName());
						}else{
							agentInfoListRes.setUserDepartmentName(null);
						}
					}else{
						agentInfoListRes.setUserDepartmentName(null);
					}
					//系统角色名称
					if(user.getRoleId() != null){
						Role role = roleService.selectById(user.getRoleId());
						if(role != null){
							agentInfoListRes.setRoleName(role.getRoleName());
						}else{
							agentInfoListRes.setRoleName(null);
						}
					}else{
						agentInfoListRes.setRoleName(null);
					}
					//userCode唯一标识
					agentInfoListRes.setUserCode(user.getUserCode());
					agentInfoList.add(agentInfoListRes);
				}
			}
		}
		return agentInfoList;
	}

	public List<AgentInfoListRes> queryUserList(String merchantCode, String projectCode){
		List<AgentInfoListRes> agentInfoList = new ArrayList<AgentInfoListRes>();
		MerchantDto entity = new MerchantDto();
		entity.setMerchantCode(merchantCode);
		Merchant merchant = merchantService.selectByDto(entity);
		if(merchant != null){
			List<SalesGroupUser> salesGroupUserList = salesGroupUserMapper.selectUserIdList(merchant.getId(), projectCode);
			if(salesGroupUserList.size() > 0){
				for(SalesGroupUser salesGroupUser : salesGroupUserList){
					UserDto userEntity = new UserDto();
					userEntity.setIsAdmin("0");
					userEntity.setId(salesGroupUser.getUserId());
					User user = userService.selectByDto(userEntity);
					if(user != null){
						AgentInfoListRes agentInfoListRes = new AgentInfoListRes();
						if(!"".equals(projectCode)){
							agentInfoListRes.setProjectCode(projectCode);
							ProjectDto projectEntity = new ProjectDto();
							projectEntity.setProjectCode(projectCode);
							Project project = projectService.selectByDto(projectEntity);
							if(project != null){
								if(project.getProjectName() != null){
									agentInfoListRes.setProjectName(project.getProjectName());
								}else{
									agentInfoListRes.setProjectName(null);
								}
							}else{
								agentInfoListRes.setProjectName(null);
							}
						}
						agentInfoListRes.setUserName(user.getUserName());//姓名
						agentInfoListRes.setMobile(user.getUserPhone());//手机号码
						//生日
						if(user.getBirthday() != null){
							agentInfoListRes.setBirthday(sdf.format(user.getBirthday()));
						}else{
							agentInfoListRes.setBirthday(null);
						}
						//入职时间
						if(user.getEntryTime() != null){
							agentInfoListRes.setEntryTime(sdf.format(user.getEntryTime()));
						}else{
							agentInfoListRes.setEntryTime(null);
						}
						//头像
						if(user.getHeadPic() != null){
							agentInfoListRes.setHeadPic(user.getHeadPic());
						}else{
							agentInfoListRes.setHeadPic(null);
						}
						//所属部门
						if(user.getUserDepartmentId() != null){
							Department department = departmentService.selectById(user.getUserDepartmentId());
							if(department != null){
								agentInfoListRes.setUserDepartmentName(department.getDepartmentName());
							}else{
								agentInfoListRes.setUserDepartmentName(null);
							}
						}else{
							agentInfoListRes.setUserDepartmentName(null);
						}
						//系统角色名称
						if(user.getRoleId() != null){
							Role role = roleService.selectById(user.getRoleId());
							if(role != null){
								agentInfoListRes.setRoleName(role.getRoleName());
							}else{
								agentInfoListRes.setRoleName(null);
							}
						}else{
							agentInfoListRes.setRoleName(null);
						}
						//userCode唯一标识
						agentInfoListRes.setUserCode(user.getUserCode());
						agentInfoList.add(agentInfoListRes);
					}
				}
			}
		}
		return agentInfoList;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 *
	 * （4）客户基本信息增量更新接口(queryCustomerInfo)
	 * @author Administrator
	 *
	 */
	@Override
	public QueryCustomerInfoResDto queryCustomerInfo(
			QueryCustomerInfoReqDto reqDto) {
		QueryCustomerInfoResDto resDto = new QueryCustomerInfoResDto();
		List<CustomerInfoListRes> customerInfoList = new ArrayList<CustomerInfoListRes>();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		Integer pageNum=reqDto.getPageNum();
		Integer pageSize=reqDto.getPageSize();
		if(null==pageNum || null==pageSize){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("pageNum或pageSize为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			MerchantDto entity = new MerchantDto();
			entity.setMerchantCode(reqDto.getToken());
			Merchant merchant = merchantService.selectByDto(entity);
			if(merchant != null){
				CustomerDto cusEntity = new CustomerDto();
				cusEntity.setMerchantId(merchant.getId());
				if(reqDto.getStarTime() != null){
					cusEntity.setUpdateTimeBefore(sdf_all.parse(reqDto.getStarTime()));
				}
				if(reqDto.getEndTime() != null){
					cusEntity.setUpdateTimeAfter(sdf_all.parse(reqDto.getEndTime()));
				}
				Page<Customer> customerPage=customerService.getPageModel(cusEntity, PageUtil.begin(pageNum, pageSize), pageSize);
				List<Customer> customerList = customerPage.getRows();
				resDto.setTotalPageNum(customerPage.getTotalPages());
				if(null!= customerList && customerList.size() > 0){
					for(Customer customer : customerList){
						CustomerInfoListRes customerInfoListRes = new CustomerInfoListRes();
						//客户所属经纪人编码
						customerInfoListRes.setCustomerAgentCode(customer.getUserCode());
						//项目名称
						ProjectDto projectDto = new ProjectDto();
						projectDto.setProjectCode(customer.getProjectCode());
						Project project = projectService.selectByDto(projectDto);
						if(project != null){
							if(project.getProjectName() != null){
								customerInfoListRes.setProjectName(project.getProjectName());
							}else{
								customerInfoListRes.setProjectName(null);
							}
						}else{
							customerInfoListRes.setProjectName(null);
						}
						//客户姓名
						customerInfoListRes.setCustomerName(customer.getCustomerName());
						//客户性别
						if(customer.getCustomerSex() != null){
							if(null!=CustomerSexEnum.getByNo(customer.getCustomerSex()))
							customerInfoListRes.setCustomerSex(CustomerSexEnum.getByNo(customer.getCustomerSex()).getDes());
						}else{
							customerInfoListRes.setCustomerSex(null);
						}
						//联系电话
						customerInfoListRes.setCustomerPhone(customer.getCustomerPhone());
						//是否星标客户
						if(customer.getCustomerStar() != null){
							if(null!=CustomerStarEnum.getByNo(customer.getCustomerStar()))
							customerInfoListRes.setCustomerStar(CustomerStarEnum.getByNo(customer.getCustomerStar()).getDes());
						}else{
							customerInfoListRes.setCustomerStar(null);
						}
						//客户来源
						if(StringUtils.isNotBlank(customer.getCustomerOrigin())){
							BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
							if(baseCodeValue != null){
								customerInfoListRes.setCustomerOrigin(baseCodeValue.getCodeName());
							}else{
								customerInfoListRes.setCustomerOrigin(null);
							}
						}

						//意向等级
						if(StringUtils.isNotEmpty(customer.getIntentionLevel())){
							if(null!=IntentionLevelEnum.getByNo(customer.getIntentionLevel()))
							customerInfoListRes.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
						}else{
							customerInfoListRes.setIntentionLevel(null);
						}
						//客户状态
						if(StringUtils.isNotEmpty(customer.getCustomerStatus())){
							if(null!=CustomerStatusEnum.getByNo(customer.getCustomerStatus()))
							customerInfoListRes.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
						}else{
							customerInfoListRes.setCustomerStatus(null);
						}
						//客户交易状态
						if(StringUtils.isNotEmpty(customer.getCustomerTradeStatus())){
							if(null!=CustomerTradeStatusEnum.getByNo(customer.getCustomerTradeStatus()))
							customerInfoListRes.setCustomerTradeStatus(CustomerTradeStatusEnum.getByNo(customer.getCustomerTradeStatus()).getDes());
						}else{
							customerInfoListRes.setCustomerTradeStatus(null);
						}
						//置业动机
						if("null" != customer.getRqTheirMotives() && StringUtils.isNotEmpty(customer.getRqTheirMotives())){
							BaseCodeValue baseCodeValue_zydj = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getRqTheirMotives()));
							if(baseCodeValue_zydj != null){
								customerInfoListRes.setRqTheirMotives(baseCodeValue_zydj.getCodeName());
							}else{
								customerInfoListRes.setRqTheirMotives(null);
							}
						}else{
							customerInfoListRes.setRqTheirMotives(null);
						}
						//关注重点
						List<CustomerFocusListRes> customerFocusList = new ArrayList<CustomerFocusListRes>();
						if(StringUtils.isNotEmpty(customer.getRqFocusId())){
							//原始存储关注重点IDS
							String focusIds[] = customer.getRqFocusId().split("[,]");
							for(int ii=0; ii<focusIds.length; ii++){
								CustomerFocusListRes cusFocusListRes = new CustomerFocusListRes();
								//cusFocusListRes.setFocusId(focusIds[ii]);
								BaseCodeValue baseCodeValue_gzzd = baseCodeValueMapper.selectEntityById(Long.valueOf(focusIds[ii]));
								if(baseCodeValue_gzzd != null){
									cusFocusListRes.setFocusName(baseCodeValue_gzzd.getCodeName());
								}
								customerFocusList.add(cusFocusListRes);
							}
							customerInfoListRes.setCustomerFocusList(customerFocusList);
						}else{
							customerInfoListRes.setCustomerFocusList(null);
						}
						//需求面积
						if(StringUtils.isNotEmpty(customer.getRqDemandArea())){
							if(null!=RqDemandAreaEnum.getByNo(customer.getRqDemandArea()))
							customerInfoListRes.setRqDemandArea(RqDemandAreaEnum.getByNo(customer.getRqDemandArea()).getDes());
						}else{
							customerInfoListRes.setRqDemandArea(null);
						}
						//预算总价
						if(StringUtils.isNotEmpty(customer.getRqBudgetSumprice())){
							if(null!=RqBudgetSumPriceEnum.getByNo(customer.getRqBudgetSumprice()))
							customerInfoListRes.setRqBudgetSumPrice(RqBudgetSumPriceEnum.getByNo(customer.getRqBudgetSumprice()).getDes());
						}else{
							customerInfoListRes.setRqBudgetSumPrice(null);
						}
						//预算单价
						if(StringUtils.isNotEmpty(customer.getRqBudgetPrice())){
							if(null!=RqBudgetPriceEnum.getByNo(customer.getRqBudgetPrice()))
							customerInfoListRes.setRqBudgetPrice(RqBudgetPriceEnum.getByNo(customer.getRqBudgetPrice()).getDes());
						}else{
							customerInfoListRes.setRqBudgetPrice(null);
						}
						//付款方式
						if(StringUtils.isNotEmpty(customer.getRqPaymentMethod())){
							if(null!=PaymentMethodEnum.getByNo(customer.getRqPaymentMethod()))
							customerInfoListRes.setRqPaymentMethod(PaymentMethodEnum.getByNo(customer.getRqPaymentMethod()).getDes());
						}else{
							customerInfoListRes.setRqPaymentMethod(null);
						}
						//需求楼层
						if(StringUtils.isNotEmpty(customer.getRqDemandFloor())){
							BaseCodeValue baseCodeValue_xqlc = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getRqDemandFloor()));
							if(baseCodeValue_xqlc != null){
								customerInfoListRes.setRqDemandFloor(baseCodeValue_xqlc.getCodeName());
							}
						}else{
							customerInfoListRes.setRqDemandFloor(null);
						}
						//生活配套
						if(StringUtils.isNotEmpty(customer.getRqLifeSupport())){
							String[]  rqLifeSupports=customer.getRqLifeSupport().split("[,]");
							String rqLifeSupportsName="";
							for(String rqLifeSupport : rqLifeSupports){
								BaseCodeValue baseCodeValue_shpt = baseCodeValueMapper.selectEntityById(Long.valueOf(rqLifeSupport));
								if(baseCodeValue_shpt != null){
									rqLifeSupportsName=rqLifeSupportsName+","+baseCodeValue_shpt.getCodeName();
								}
							}
							customerInfoListRes.setRqLifeSupport(rqLifeSupportsName);

						}else{
							customerInfoListRes.setRqLifeSupport(null);
						}
						//生活服务
						if(StringUtils.isNotBlank(customer.getRqServicesId())){
							String[]  rqServicesIds=customer.getRqServicesId().split("[,]");
							String  rqServicesIdsName="";
							for(String rqServicesId : rqServicesIds){
								BaseCodeValue baseCodeValue_shfw = baseCodeValueMapper.selectEntityById(Long.valueOf(rqServicesId));
								if(baseCodeValue_shfw != null){
									rqServicesIdsName=rqServicesIdsName+","+baseCodeValue_shfw.getCodeName();
								}
							}
							customerInfoListRes.setRqServices(rqServicesIdsName);
						}else{
							customerInfoListRes.setRqServices(null);
						}
						//庭院需求面积
						if(customer.getRqCourtyardArea()!=null){
							customerInfoListRes.setRqCourtyardArea(String.valueOf(customer.getRqCourtyardArea()));
						}else{
							customerInfoListRes.setRqCourtyardArea(null);
						}
						//希望庭院具备功能
						if(StringUtils.isNotEmpty(customer.getRqCourtyardFunction())){
							BaseCodeValue baseCodeValue_tyjbgn = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getRqCourtyardFunction()));
							if(baseCodeValue_tyjbgn != null){
								customerInfoListRes.setRqCourtyardFunction(baseCodeValue_tyjbgn.getCodeName());
							}
						}else{
							customerInfoListRes.setRqCourtyardFunction(null);
						}
						//首次接触方式
						if(StringUtils.isNotEmpty(customer.getFtContactWay())){
							BaseCodeValue baseCodeValue_scjcfs = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getFtContactWay()));
							if(baseCodeValue_scjcfs != null){
								customerInfoListRes.setFtContactWay(baseCodeValue_scjcfs.getCodeName());
							}
						}else{
							customerInfoListRes.setFtContactWay(null);
						}
						//首次接触时间
						if(customer.getFtContactTime() != null){
							customerInfoListRes.setFtContactTime(sdf.format(customer.getFtContactTime()));
						}else{
							customerInfoListRes.setFtContactTime(null);
						}
						//首次接触内容
						if(customer.getFtContactContent() !=null){
							customerInfoListRes.setFtContactContent(customer.getFtContactContent());
						}else{
							customerInfoListRes.setFtContactContent(null);
						}
						//证件类型
						if(StringUtils.isNotEmpty(customer.getPeDocumentType())){
							BaseCodeValue baseCodeValue_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getPeDocumentType()));
							if(baseCodeValue_zjlx != null){
								customerInfoListRes.setPeDocumentType(baseCodeValue_zjlx.getCodeName());
							}
						}else{
							customerInfoListRes.setPeDocumentType(null);
						}
						//证件号码
						if(customer.getPeDocumentNumber() !=null){
							customerInfoListRes.setPeDocumentNumber(customer.getPeDocumentNumber());
						}else{
							customerInfoListRes.setPeDocumentNumber(null);
						}
						//出生日期
						if(customer.getPeBirth() !=null){
							customerInfoListRes.setPeBirth(customer.getPeBirth());
						}else{
							customerInfoListRes.setPeBirth(null);
						}
						//年龄
						if(customer.getPeAge() != null){
							customerInfoListRes.setPeAge(customer.getPeAge());
						}else{
							customerInfoListRes.setPeAge(null);
						}
						//学历
						if(StringUtils.isNotEmpty(customer.getPeAcademicQualifications())){
							BaseCodeValue baseCodeValue_xl = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getPeAcademicQualifications()));
							if(baseCodeValue_xl != null){
								customerInfoListRes.setPeAcademicQualifications(baseCodeValue_xl.getCodeName());
							}
						}else{
							customerInfoListRes.setPeAcademicQualifications(null);
						}
						//固话
						if(customer.getPeTelephone() !=null){
							customerInfoListRes.setPeTelephone(customer.getPeTelephone());
						}else{
							customerInfoListRes.setPeTelephone(null);
						}
						//手机号码
						if(customer.getPeMobile() != null){
							customerInfoListRes.setPeMobile(customer.getPeMobile());
						}else{
							customerInfoListRes.setPeMobile(null);
						}
						//微信
						if(customer.getPeWechat() !=null){
							customerInfoListRes.setPeWechat(customer.getPeWechat());
						}else{
							customerInfoListRes.setPeWechat(null);
						}
						//邮箱
						if(customer.getPeEmail() != null){
							customerInfoListRes.setPeEmail(customer.getPeEmail());
						}else{
							customerInfoListRes.setPeEmail(null);
						}
						//邮编
						if(customer.getPePostcode() !=null){
							customerInfoListRes.setPePostcode(customer.getPePostcode());
						}else{
							customerInfoListRes.setPePostcode(null);
						}
						//户籍所在地
						if(customer.getPeDomicilePlace() !=null){
							customerInfoListRes.setPeDomicilePlace(customer.getPeDomicilePlace());
						}else{
							customerInfoListRes.setPeDomicilePlace(null);
						}
						//联系地址
						if(customer.getPeContactAddress() != null){
							customerInfoListRes.setPeContactAddress(customer.getPeContactAddress());
						}else{
							customerInfoListRes.setPeContactAddress(null);
						}
						//小区名
						if(customer.getPePlot() != null){
							customerInfoListRes.setPePlot(customer.getPePlot());
						}else{
							customerInfoListRes.setPePlot(null);
						}
						//详细地址(小区)
						if(customer.getPeDetailedAddress() != null){
							customerInfoListRes.setPeDetailedAddress(customer.getPeDetailedAddress());
						}else{
							customerInfoListRes.setPeDetailedAddress(null);
						}
						//详情地址(工作区)
						if(customer.getPeWorkaroundAddress() != null){
							customerInfoListRes.setPeWorkaroundAddress(customer.getPeWorkaroundAddress());
						}else{
							customerInfoListRes.setPeWorkaroundAddress(null);
						}
						//车架品牌信息
						if(customer.getPeFrameBrandId()!=null){
							BaseCodeValue baseCodeValue_cjpp = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getPeFrameBrandId()));
							if(baseCodeValue_cjpp != null){
								customerInfoListRes.setPeFrameBrand(baseCodeValue_cjpp.getCodeName());
							}
						}else{
							customerInfoListRes.setPeFrameBrand(null);
						}
						//家庭年收入
						if(StringUtils.isNotEmpty(customer.getPeHouseholdIncome())){
							customerInfoListRes.setPeHouseholdIncome(PeHouseholdIncomeEnum.getByNo(customer.getPeHouseholdIncome()).getDes());
						}else{
							customerInfoListRes.setPeHouseholdIncome(null);
						}
						//兴趣爱好
						if(StringUtils.isNotBlank(customer.getPeHobbyId())){
							String[] peHobbyIds=customer.getPeHobbyId().split("[,]");
							String peHobbyIdName="";
							for(String peHobbyId : peHobbyIds){
								BaseCodeValue baseCodeValue_shpt = baseCodeValueMapper.selectEntityById(Long.valueOf(peHobbyId));
								if(baseCodeValue_shpt != null){
									peHobbyIdName=peHobbyIdName+","+baseCodeValue_shpt.getCodeName();
								}
							}
							customerInfoListRes.setPeHobby(peHobbyIdName);
						}else{
							customerInfoListRes.setPeHobby(null);
						}
						//乐于参加的活动类型
						if(StringUtils.isNotEmpty(customer.getPeActivityType())){
							String[]  peActivityTypes=customer.getPeActivityType().split("[,]");
							String  peActivityTypesName="";
							for(String peActivityType : peActivityTypes){
								BaseCodeValue baseCodeValue_shfw = baseCodeValueMapper.selectEntityById(Long.valueOf(peActivityType));
								if(baseCodeValue_shfw != null){
									peActivityTypesName=peActivityTypesName+","+baseCodeValue_shfw.getCodeName();
								}
							}
							customerInfoListRes.setPeActivityType(peActivityTypesName);
						}else{
							customerInfoListRes.setPeActivityType(null);
						}
						//结婚纪念日
						if(customer.getPeWeddingDate() != null){
							customerInfoListRes.setPeWeddingDate(sdf.format(customer.getPeWeddingDate()));
						}else{
							customerInfoListRes.setPeWeddingDate(null);
						}
						//本地购房次数
						if(customer.getReLocalPurchase() != null){
							customerInfoListRes.setReLocalPurchase(String.valueOf(customer.getReLocalPurchase()));
						}else{
							customerInfoListRes.setReLocalPurchase(null);
						}
						//目前家庭持有住宅数
						if(customer.getReCurrentHoldings() != null){
							customerInfoListRes.setReCurrentHoldings(String.valueOf(customer.getReCurrentHoldings()));
						}else{
							customerInfoListRes.setReCurrentHoldings(null);
						}
						//目前家庭住宅已按揭数
						if(customer.getReResidentialMortgage() != null){
							customerInfoListRes.setReResidentialMortgage(String.valueOf(customer.getReResidentialMortgage()));
						}else{
							customerInfoListRes.setReResidentialMortgage(null);
						}
						//目前居住的物业类型
						if(StringUtils.isNotEmpty(customer.getReCurrentlyProperty())){
							BaseCodeValue baseCodeValue_wylx = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getReCurrentlyProperty()));
							if(baseCodeValue_wylx != null){
								customerInfoListRes.setReCurrentlyProperty(baseCodeValue_wylx.getCodeName());
							}
						}else{
							customerInfoListRes.setReCurrentlyProperty(null);
						}
						//目前居住的面积
						if(StringUtils.isNotEmpty(customer.getReCurrentlyArea())){
							if(null!=ReCurrentlyAreaEnum.getByNo(customer.getReCurrentlyArea()))
							customerInfoListRes.setReCurrentlyArea(ReCurrentlyAreaEnum.getByNo(customer.getReCurrentlyArea()).getDes());
						}else{
							customerInfoListRes.setReCurrentlyArea(null);
						}
						//目前居住的物业结构
						if(StringUtils.isNotEmpty(customer.getReCurrentlyStructure())){
							BaseCodeValue baseCodeValue_mqjzdhxjg = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getReCurrentlyStructure()));
							if(baseCodeValue_mqjzdhxjg != null){
								customerInfoListRes.setReCurrentlyStructure(baseCodeValue_mqjzdhxjg.getCodeName());
							}
						}else{
							customerInfoListRes.setReCurrentlyStructure(null);
						}
						//目前居住/办公的房子属性
						if(StringUtils.isNotEmpty(customer.getReCurrentlyHouse())){
							BaseCodeValue baseCodeValue_mqjzfzsx = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getReCurrentlyHouse()));
							if(baseCodeValue_mqjzfzsx != null){
								customerInfoListRes.setReCurrentlyHouse(baseCodeValue_mqjzfzsx.getCodeName());
							}
						}else{
							customerInfoListRes.setReCurrentlyHouse(null);
						}
						//工作日联系时间
						if(StringUtils.isNotEmpty(customer.getCoContactTime())){
							if(null!=CoContactTimeEnum.getByNo(customer.getCoContactTime()))
							customerInfoListRes.setCoContactTime(CoContactTimeEnum.getByNo(customer.getCoContactTime()).getDes());
						}else{
							customerInfoListRes.setCoContactTime(null);
						}
						//工作日联系方式
						if(StringUtils.isNotEmpty(customer.getCoInformationDays())){
							BaseCodeValue baseCodeValue_gzlxfs = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCoInformationDays()));
							if(baseCodeValue_gzlxfs != null){
								customerInfoListRes.setCoInformationDays(baseCodeValue_gzlxfs.getCodeName());
							}
						}else{
							customerInfoListRes.setCoInformationDays(null);
						}
						//周末联系时间
						if(StringUtils.isNotEmpty(customer.getCoContactWeekend())){
							if(null!=CoContactWeekendEnum.getByNo(customer.getCoContactWeekend()))
							customerInfoListRes.setCoContactWeekend(CoContactWeekendEnum.getByNo(customer.getCoContactWeekend()).getDes());
						}else{
							customerInfoListRes.setCoContactWeekend(null);
						}
						//周末联系方式
						if(StringUtils.isNotEmpty(customer.getCoWeekendInformation())){
							BaseCodeValue baseCodeValue_zmlxfs = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCoWeekendInformation()));
							if(baseCodeValue_zmlxfs != null){
								customerInfoListRes.setCoWeekendInformation(baseCodeValue_zmlxfs.getCodeName());
							}
						}else{
							customerInfoListRes.setCoWeekendInformation(null);
						}
						//是否分配
						if(StringUtils.isNotBlank(customer.getIsDistribution())){
							customerInfoListRes.setIsDistribution(IsDistributionEnum.getByNo(customer.getIsDistribution()).getDes());
						}else{
							customerInfoListRes.setIsDistribution(null);
						}
						//最后跟进时间
						if(customer.getLastFollowTime() != null){
							customerInfoListRes.setLastFollowTime(sdf_all.format(customer.getLastFollowTime()));
						}else{
							customerInfoListRes.setLastFollowTime(null);
						}
						//客户唯一标识
						customerInfoListRes.setCustomerCode(customer.getCustomerCode());
						customerInfoList.add(customerInfoListRes);
					}
					resDto.setCustomerInfoList(customerInfoList);
				}else{
					resDto.setCustomerInfoList(null);
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("客户基本信息增量查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 *
	 * （5）客户跟进信息增量更新接口(queryCustomerFollowInfo)
	 * @author Administrator
	 *
	 */
	@Override
	public QueryCustomerFollowInfoResDto queryCustomerFollowInfo(
			QueryCustomerFollowInfoReqDto reqDto) {
		QueryCustomerFollowInfoResDto resDto = new QueryCustomerFollowInfoResDto();
		List<CustomerFollowInfoListRes> customerFollowInfoList = new ArrayList<CustomerFollowInfoListRes>();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		Integer pageNum=reqDto.getPageNum();
		Integer pageSize=reqDto.getPageSize();
		if(null==pageNum || null==pageSize){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("pageNum或pageSize为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			MerchantDto entity = new MerchantDto();
			entity.setMerchantCode(reqDto.getToken());
			Merchant merchant = merchantService.selectByDto(entity);
			if(merchant != null){
				FollowDto followDto = new FollowDto();
				followDto.setMerchantId(merchant.getId());
				followDto.setCreateTimeBefore(sdf_all.parse(reqDto.getStarTime()));
				followDto.setCreateTimeAfter(sdf_all.parse(reqDto.getEndTime()));
				Page<Follow> followPage=followService.getPageModel(followDto, PageUtil.begin(pageNum, pageSize), pageSize);
				List<Follow> followList = followPage.getRows();
				resDto.setTotalPageNum(followPage.getTotalPages());
				if(null!=followList && followList.size() > 0){
					for(Follow follow : followList){
						CustomerFollowInfoListRes customerFollowInfoListRes = new CustomerFollowInfoListRes();
						//项目名称
						ProjectDto projectDto = new ProjectDto();
						projectDto.setProjectCode(follow.getProjectCode());
						Project project = projectService.selectByDto(projectDto);
						if(project != null){
							if(project.getProjectName() != null){
								customerFollowInfoListRes.setProjectName(project.getProjectName());
							}else{
								customerFollowInfoListRes.setProjectName(null);
							}
						}else{
							customerFollowInfoListRes.setProjectName(null);
						}
						//客户名称
						if(follow.getCustomerId() != null){
							Customer customer = customerService.selectById(follow.getCustomerId());
							if(customer != null){
								if(customer.getCustomerName() != null){
									customerFollowInfoListRes.setCustomerName(customer.getCustomerName());
								}else{
									customerFollowInfoListRes.setCustomerName(null);
								}
								//客户编码
								if(customer.getCustomerCode() != null){
									customerFollowInfoListRes.setCustomerCode(customer.getCustomerCode());
								}else{
									customerFollowInfoListRes.setCustomerCode(null);
								}
							}else{
								customerFollowInfoListRes.setCustomerName(null);
							}
						}else{
							customerFollowInfoListRes.setCustomerName(null);
						}
						//跟进方式
						if(follow.getFollowMode() != null){
							customerFollowInfoListRes.setFollowMode(FollowModeEnum.getByNo(follow.getFollowMode()).getDes());
						}else{
							customerFollowInfoListRes.setFollowMode(null);
						}
						//跟进时间
						if(follow.getFollowTime() != null){
							customerFollowInfoListRes.setFollowTime(sdf_all.format(follow.getFollowTime()));
						}else{
							customerFollowInfoListRes.setFollowTime(null);
						}
						//跟进类型
						if(follow.getFollowType() != null){
							customerFollowInfoListRes.setFollowType(FollowTypeEnum.getByNo(follow.getFollowType()).getDes());
						}else{
							customerFollowInfoListRes.setFollowType(null);
						}
						//跟进内容
						if(follow.getFollowContent() != null){
							customerFollowInfoListRes.setFollowContent(follow.getFollowContent());
						}else{
							customerFollowInfoListRes.setFollowContent(null);
						}
						//语音时长
						if(follow.getVoiceTime() != null && !"".equals(follow.getVoiceTime())){
							customerFollowInfoListRes.setVoiceTime(follow.getVoiceTime());
						}else{
							customerFollowInfoListRes.setVoiceTime(null);
						}
						//项目code
						customerFollowInfoListRes.setProjectCode(follow.getProjectCode());
						//经纪人code
						customerFollowInfoListRes.setUserCode(follow.getUserCode());
						//跟进code【跟进Id】
						customerFollowInfoListRes.setFollowCode(String.valueOf(follow.getId()));
						customerFollowInfoList.add(customerFollowInfoListRes);
					}
					resDto.setCustomerFollowInfoList(customerFollowInfoList);
				}else{
					resDto.setCustomerFollowInfoList(null);
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("客户跟进信息增量查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 基本信息类接口（绿城扩展POM）
	 *
	 * （1）项目信息查询接口(queryProjectInfoPom)
	 * @param reqDto 业务审核请求信息
	 * @return 操作结果
	 */
	@Override
	public QueryProjectInfoPomResDto queryProjectInfoPom(
			QueryProjectInfoPomReqDto reqDto) {
		QueryProjectInfoPomResDto resDto = new QueryProjectInfoPomResDto();
		List<ProjectInfoPomListRes> projectInfoPomList = new ArrayList<ProjectInfoPomListRes>();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			MerchantDto entity = new MerchantDto();
			entity.setMerchantCode(reqDto.getToken());
			Merchant merchant = merchantService.selectByDto(entity);
			if(merchant != null){
				ProjectDto proEntity = new ProjectDto();
				proEntity.setMerchantId(merchant.getId());
				List<Project> projectList = projectService.selectListByDto(proEntity);
				if(projectList.size() > 0){
					for(Project pro : projectList){
						ProjectInfoPomListRes projectInfoPomListRes = new ProjectInfoPomListRes();
						//项目主表信息
						projectInfoPomListRes.setProjectCode(pro.getProjectCode());//项目code
						projectInfoPomListRes.setProjectName(pro.getProjectName());//项目名称
						projectInfoPomListRes.setSalesAddress(pro.getSalesAddress());//售楼地址
						projectInfoPomListRes.setSalesHotline(pro.getSalesHotline());//销售热线
						projectInfoPomListRes.setPremisesCase(pro.getPremisesCase());//楼盘概况
						projectInfoPomListRes.setPropertyCompany(pro.getPropertyCompany());//物业公司
						projectInfoPomListRes.setCarportMatching(pro.getCarportMatching());//车位配比

						//项目子表信息Info
						ProjectInfoDto projectInfoDto = new ProjectInfoDto();
						projectInfoDto.setProjectId(pro.getId());
						ProjectInfo projectInfo = projectInfoService.selectByDto(projectInfoDto);
						if(projectInfo != null){
							//自持面积
							if(projectInfo.getOwnArea() != null){
								projectInfoPomListRes.setOwnArea(String.valueOf(projectInfo.getOwnArea()));
							}else{
								projectInfoPomListRes.setOwnArea(null);
							}
							//地下停车场面积
							if(projectInfo.getUndergroundParkingArea() != null){
								projectInfoPomListRes.setUndergroundParkingArea(String.valueOf(projectInfo.getUndergroundParkingArea()));
							}else{
								projectInfoPomListRes.setUndergroundParkingArea(null);
							}
							//地下停车场数量
							if(projectInfo.getUndergroundParkingNum() != null){
								projectInfoPomListRes.setUndergroundParkingNum(String.valueOf(projectInfo.getUndergroundParkingNum()));
							}else{
								projectInfoPomListRes.setUndergroundParkingNum(null);
							}
							//车位数
							if(projectInfo.getParking() != null){
								projectInfoPomListRes.setCarportTotal(String.valueOf(projectInfo.getParking()));
							}else{
								projectInfoPomListRes.setCarportTotal(null);
							}
							//地上机动车位
							if(projectInfo.getGroundMotor() != null){
								projectInfoPomListRes.setGroundMotor(String.valueOf(projectInfo.getGroundMotor()));
							}else{
								projectInfoPomListRes.setGroundMotor(null);
							}
							//地下机动车位
							if(projectInfo.getUndergroundMotor() != null){
								projectInfoPomListRes.setUndergroundMotor(String.valueOf(projectInfo.getUndergroundMotor()));
							}else{
								projectInfoPomListRes.setUndergroundMotor(null);
							}
							//地上非机动车位
							if(projectInfo.getGroundNonMotor() != null){
								projectInfoPomListRes.setGroundNonMotor(String.valueOf(projectInfo.getGroundNonMotor()));
							}else{
								projectInfoPomListRes.setGroundNonMotor(null);
							}
							//地下非机动车位
							if(projectInfo.getUndergroundNonMotor() != null){
								projectInfoPomListRes.setUndergroundNonMotor(String.valueOf(projectInfo.getUndergroundNonMotor()));
							}else{
								projectInfoPomListRes.setUndergroundNonMotor(null);
							}
							//地上可售面积
							if(projectInfo.getGroundArea() != null){
								projectInfoPomListRes.setGroundSalableArea(String.valueOf(projectInfo.getGroundArea()));
							}else{
								projectInfoPomListRes.setGroundSalableArea(null);
							}
							//地下可售面积
							if(projectInfo.getUndergroundArea() != null){
								projectInfoPomListRes.setUndergroundSalableArea(String.valueOf(projectInfo.getUndergroundArea()));
							}else{
								projectInfoPomListRes.setUndergroundSalableArea(null);
							}
						}

						//待定义，暂返回null
						projectInfoPomListRes.setPlanningSalableArea(null);//规划可售面积
						projectInfoPomListRes.setUnitNum(null);//单元数
						projectInfoPomListRes.setFloorNum(null);//层数
						projectInfoPomListRes.setGroundRentArea(null);//地上可租面积
						projectInfoPomListRes.setUndergroundRentArea(null);//地下可租面积
						projectInfoPomListRes.setSingleParkingAmount(null);//单套车位金额
						projectInfoPomListRes.setExpectedSaleAmount(null);//预计销售金额
						projectInfoPomListRes.setSalesAveragePrice(null);//销售均价

						//房源信息表
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setProjectId(pro.getId());
						projectRoomDto.setMerchantId(pro.getMerchantId());
						projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
						List<ProjectRoom> projectRoomList = projectRoomService.selectListByDto(projectRoomDto);
						if(projectRoomList.size() > 0){
							Double innerArea = 0.00;
							Double freeArea = 0.00;
							Double buildingArea = 0.00;
							for(ProjectRoom projectRoom : projectRoomList){
								innerArea += Double.valueOf(String.valueOf(projectRoom.getInnerArea()));
								freeArea += Double.valueOf(String.valueOf(projectRoom.getFreeArea()));
								buildingArea += Double.valueOf(String.valueOf(projectRoom.getBuildingArea()));
							}
							projectInfoPomListRes.setInnerArea(df_zero.format(innerArea));//套内面积
							projectInfoPomListRes.setFreeArea(df_zero.format(freeArea));//赠送面积
							projectInfoPomListRes.setSumSalableArea(df_zero.format(buildingArea));//总可售面积
							projectInfoPomListRes.setSalablePloidy(String.valueOf(projectRoomList.size()));//可售套数
						}else{
							projectInfoPomListRes.setInnerArea(null);//套内面积
							projectInfoPomListRes.setFreeArea(null);//赠送面积
							projectInfoPomListRes.setSumSalableArea(null);//总可售面积
							projectInfoPomListRes.setSalablePloidy(String.valueOf(0));//可售套数
						}

						//总平图列表
						List<ProjectImg> projectImgList = queryProjectImgList(pro.getId(),"2");
						List<SumPlanListRes> sumPlanList = new ArrayList<SumPlanListRes>();
						if(projectImgList.size() > 0){
							for(ProjectImg proImg : projectImgList){
								if(proImg.getSmallUrl() != null){
									SumPlanListRes sumPlanListRes = new SumPlanListRes();
									sumPlanListRes.setSumPlanUrl(proImg.getSmallUrl());
									sumPlanList.add(sumPlanListRes);
								}
							}
							projectInfoPomListRes.setSumPlanList(sumPlanList);
						}else{
							projectInfoPomListRes.setSumPlanList(null);
						}

						//效果图列表
						List<ProjectImg> projectImgList2 = queryProjectImgList(pro.getId(),"3");
						List<CirCumListRes> cirCumList = new ArrayList<CirCumListRes>();
						if(projectImgList2.size() > 0){
							for(ProjectImg proImg2 : projectImgList2){
								if(proImg2.getSmallUrl() != null){
									CirCumListRes cirCumListRes = new CirCumListRes();
									cirCumListRes.setCirCumUrl(proImg2.getSmallUrl());
									cirCumList.add(cirCumListRes);
								}
							}
							projectInfoPomListRes.setCirCumList(cirCumList);
						}else{
							projectInfoPomListRes.setCirCumList(null);
						}

						//样板图列表
						List<ProjectImg> projectImgList3 = queryProjectImgList(pro.getId(),"6");
						List<ModelListRes> modelList = new ArrayList<ModelListRes>();
						if(projectImgList3.size() > 0){
							for(ProjectImg proImg3 : projectImgList3){
								if(proImg3.getSmallUrl() != null){
									ModelListRes modelListRes = new ModelListRes();
									modelListRes.setModelUrl(proImg3.getSmallUrl());
									modelList.add(modelListRes);
								}
							}
							projectInfoPomListRes.setModelList(modelList);
						}else{
							projectInfoPomListRes.setModelList(null);
						}

						//实景图列表
						List<ProjectImg> projectImgList4 = queryProjectImgList(pro.getId(),"5");
						List<LiveActionListRes> liveActionList = new ArrayList<LiveActionListRes>();
						if(projectImgList4.size() > 0){
							for(ProjectImg proImg4 : projectImgList4){
								if(proImg4.getSmallUrl() != null){
									LiveActionListRes liveActionListRes = new LiveActionListRes();
									liveActionListRes.setLiveActionUrl(proImg4.getSmallUrl());
									liveActionList.add(liveActionListRes);
								}
							}
							projectInfoPomListRes.setLiveActionList(liveActionList);
						}else{
							projectInfoPomListRes.setLiveActionList(null);
						}
						projectInfoPomList.add(projectInfoPomListRes);
					}
					resDto.setProjectInfoPomList(projectInfoPomList);
				}else{
					resDto.setProjectInfoPomList(null);
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("项目信息POM查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 项目类型图片列表
	 * @param id
	 * @param type
	 * @return projectImgList
	 */
	public List<ProjectImg> queryProjectImgList(Long id, String type){
		List<ProjectImg> projectImgList = new ArrayList<ProjectImg>();
		ProjectImgDto ProjectImgDto = new ProjectImgDto();
		ProjectImgDto.setProjectId(id);
		ProjectImgDto.setProjectImgType(type);
		List<ProjectImg> proImgList = projectImgService.selectListByDto(ProjectImgDto);
		if(proImgList.size() > 0){
			for(ProjectImg proImg : proImgList){
				ProjectImg projectImg = new ProjectImg();
				projectImg.setSmallUrl(proImg.getSmallUrl());
				projectImgList.add(projectImg);
			}
		}
		return projectImgList;
	}

	/**
	 * M2向渠道提供项目信息
	 * @author Administrator
	 *
	 */
	@Override
	public MCQueryProjectResDto mcQueryProject(MCQueryProjectReqDto reqDto) {
		MCQueryProjectResDto resDto = new MCQueryProjectResDto();
		List<MCProjectListRes> resList = new ArrayList<>();
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			Integer begin = reqDto.getPageNumber();
			Integer row = reqDto.getPageSize();
			MerchantDto entity = new MerchantDto();
			entity.setMerchantCode(reqDto.getMerchantCode());
			Merchant merchant = merchantService.selectByDto(entity);
			if(merchant != null){
				ProjectDto proEntity = new ProjectDto();
				proEntity.setMerchantId(merchant.getId());
				proEntity.setProjectName(reqDto.getProjectName());
				Page<Project> projectPage = projectService.getPageModel(proEntity, PageUtil.begin(begin, row), row);
				Page<MCProjectListRes> resPage = new Page<>();
				if(null != projectPage && projectPage.getRows().size() > 0){
					resPage.setPageSize(projectPage.getPageSize());
					resPage.setPageNumber(begin);
					resPage.setTotal(projectPage.getTotal());
					resPage.setTotalPages(projectPage.getTotalPages());
					for(Project pro : projectPage.getRows()){
						MCProjectListRes mcProjectListRes = new MCProjectListRes();
						mcProjectListRes.setProjectCode(pro.getProjectCode());//项目code
						mcProjectListRes.setProjectName(pro.getProjectName());//项目名称
						resList.add(mcProjectListRes);
					}
					resPage.setRows(resList);
					resDto.setResPage(resPage);
				}else{
					resDto.setResPage(resPage);
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("项目信息查询失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	@Override
	public MCCusUniqueResDto mcCusUniqueValidate(MCCusUniqueReqDto reqDto) {
		MCCusUniqueResDto resDto = new MCCusUniqueResDto();
		String isExists = "false";
		resDto.setIsExists(isExists);
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			MerchantDto entity = new MerchantDto();
			entity.setMerchantCode(reqDto.getMerchantCode());
			Merchant merchant = merchantService.selectByDto(entity);
			if(merchant != null){
				CustomerDto cusDto = new CustomerDto();
				cusDto.setCustomerPhone(reqDto.getCustomerPhone());
				cusDto.setMerchantId(merchant.getId());
				cusDto.setProjectCode(reqDto.getProjectCode());
				List<Customer> cusList = customerService.selectCustomerPhoneByListPC(cusDto);
				if(null != cusList && cusList.size() > 0){
					isExists = "true";
				}
			}
			resDto.setIsExists(isExists);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("客户校验失败:" + e);
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	///////////////////////////////////////////////判断客户意向等级///////////////////////////////////////////////////////////////

	/**
	 * 验证客户信息意向登记
	 * 1.A+，
	 * 2.A
	 * 3.B
	 * 4.C
	 * 5.D
	 * 高等级包含低等级验证
	 * @param reqDto
	 * @return
	 */
	private boolean checkIntentionLevel(CheckCustomerIntentionReqDto reqDto){
		if(reqDto == null){
			return false;
		}
		//B,C,D等级
		if( "3".equals(reqDto.getIntentionLevel() ) || "4".equals(reqDto.getIntentionLevel() ) ||  "5".equals(reqDto.getIntentionLevel() )){
			if(checkB(reqDto)){
				return true;
			}else{
				return false;
			}
		}
		//A等级
		if("2".equals(reqDto.getIntentionLevel())){
			if(checkA(reqDto)){
				return true;
			}else{
				return false;
			}
		}
		//A+等级
		//以去除当前等级,与A保持一致
		if("1".equals(reqDto.getIntentionLevel())){
			if(checkA(reqDto)){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}

	//1.项目名称，2.客户名称，3客户性别，4联系电话，5客户状态，6获知途径，7客户性质，8接触方式，9接触时间，10沟通方式
	private static boolean checkD(CheckCustomerIntentionReqDto reqDto){
		if(reqDto.getProjectId() == null && StringUtils.isEmpty(reqDto.getProjectCode())){//项目名称
			return false;
		}
		if(StringUtils.isEmpty(reqDto.getCustomerName())){//客户名称
			return false;
		}
		if(StringUtils.isEmpty(reqDto.getCustomerSex())){//客户性别
			return false;
		}
		if(StringUtils.isEmpty(reqDto.getCustomerPhone())){//联系电话
			return false;
		}
		/*if(StringUtils.isEmpty(reqDto.getCustomerStatus())){//客户状态
			return false;
		}*/
		if(StringUtils.isEmpty(reqDto.getInformedWay())){//获知途径
			return false;
		}
		/*if(StringUtils.isEmpty(reqDto.getCustomerOrigin())){//客户性质
			return false;
		}
		if(StringUtils.isEmpty(reqDto.getFtContactWay())){//接触方式
			return false;
		}
		if(reqDto.getFtContactTime() == null){//接触时间
			return false;
		}
		if(StringUtils.isEmpty(reqDto.getFtContactContent())){//沟通内容
			return false;
		}*/
		return true;
	}
	private static boolean checkC(CheckCustomerIntentionReqDto reqDto){
		if(checkD(reqDto)){
			return true;
		}
		return false;
	}
	private static boolean checkB(CheckCustomerIntentionReqDto reqDto){
		if(checkC(reqDto)){
			return true;
		}
		return false;
	}
	private static boolean checkA(CheckCustomerIntentionReqDto reqDto){
		if(checkB(reqDto)){
			if(StringUtils.isEmpty(reqDto.getRqTheirMotives())){
				return  false;
			}
			if(StringUtils.isEmpty(reqDto.getRqDemandArea())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getRqServicesId())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getRqFocusId())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getRqPaymentMethod())){
				return false;
			}
			if((reqDto.getPeResidenceProvinceId()) == null){
				return false;
			}
			if(reqDto.getPeResidenceCityId() == null){
				return false;
			}
			if(reqDto.getPeResidenceAreaId() == null){
				return false;
			}
			if(reqDto.getPeWorkaroundProvinceId() == null){
				return false;
			}
			if(reqDto.getPeWorkaroundCityId() == null){
				return false;
			}
			if(reqDto.getPeWorkaroundAreaId() == null){
				return false;
			}
			/*if(reqDto.getRoomList() == null || reqDto.getRoomList().size() == 0){
				return false;
			}*/
			if(StringUtils.isEmpty(reqDto.getIndustry())){
				return false;
			}
			return true;
		}
		return false;
	}
	private static boolean checkAj(CheckCustomerIntentionReqDto reqDto){
		if(checkB(reqDto) && checkA(reqDto)){
			if(StringUtils.isEmpty(reqDto.getPeContactAddress())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getPeDocumentType())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getPeDocumentNumber())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getPeBirth())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getPeDomicilePlace())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getDailyInformation())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getPeHobbyId())){
				return false;
			}
			if(StringUtils.isEmpty(reqDto.getPeActivityType())){
				return false;
			}
			return true;
		}
		return false;
	}
	private boolean checkIsA(Long id){
		Customer customer = customerService.selectById(id);
		if(customer == null){
			return false;
		}
		if( "1".equals(customer.getIntentionLevel()) || "2".equals(customer.getIntentionLevel())){
			return true;
		}else{
			return false;
		}
	}
	///////////////////////////////////////////////判断客户意向等级///////////////////////////////////////////////////////////////
	@Override
	public QueryProjectQuestionnaireListResDto queryQuestionnaireList(QueryProjectQuestionnaireListReqDto reqDto) {
		QueryProjectQuestionnaireListResDto resDto = new QueryProjectQuestionnaireListResDto();
		List<AppProjectQuestionnaire> appProjectQuestionnaireList = new ArrayList<AppProjectQuestionnaire>();
		boolean flag = true; //DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		try{
			ProjectQuestionnaireDto pqDto = new ProjectQuestionnaireDto();
			pqDto.setProjectId(reqDto.getProjectId());
			pqDto.setIsValid(IsValidEnum.VALID.getNo());
			pqDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<ProjectQuestionnaire> projectQuestionnaireList = projectQuestionnaireService.selectListByDto(pqDto);
			if(null != projectQuestionnaireList && projectQuestionnaireList.size() > 0){
				for(ProjectQuestionnaire pq: projectQuestionnaireList){
					AppProjectQuestionnaire appProjectQuestionnaire = new AppProjectQuestionnaire();
					appProjectQuestionnaire.setMerchantId(String.valueOf(pq.getMerchantId()));
					appProjectQuestionnaire.setProjectId(String.valueOf(pq.getProjectId()));
					appProjectQuestionnaire.setQuestionnaireId(String.valueOf(pq.getId()));
					appProjectQuestionnaire.setQuestionnaireName(pq.getName());
					appProjectQuestionnaire.setAnswerUrl("/appapi/questionnaire");
					appProjectQuestionnaireList.add(appProjectQuestionnaire);
				}
			}
			resDto.setAppProjectQuestionnaireList(appProjectQuestionnaireList);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("客户校验失败:" + e);
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 查询签约分页接口
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetSignedPageResDto getSignedPage(GetSignedPageReqDto reqDto) {
		GetSignedPageResDto resDto = new GetSignedPageResDto();
		try {
			Integer begin = reqDto.getPageNumber();
			Integer row = reqDto.getPageSize();
			if(begin == null || row == null) {
				resDto.setErrorMsg("分页字段不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			String userId = reqDto.getUserId();
			if (StringUtils.isEmpty(userId)) {
				resDto.setErrorMsg("经纪人ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long merchantId = reqDto.getMerchantId();
			if (merchantId == null) {
				resDto.setErrorMsg("商户ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long projectId = reqDto.getProjectId();
			if (projectId == null) {
				resDto.setErrorMsg("项目ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}

			SignedDto entity = new SignedDto();
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService
						.dataPermissionCondition(Long.parseLong(reqDto.getUserId()), "menu_0005_0005", null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				entity.setDataPermission(dataPermissionArr[1]);
			}
			entity.setSql(reqDto.getQueryConditions());
			entity.setMerchantId(merchantId);
			entity.setProjectId(projectId);
			entity.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			entity.setM_businessStatus(" AND t.business_status IN (1, 4)");
			entity.setIsStatusTrue("1"); //只查询有效的签约（状态为签约和更名）
			entity.setOrders(" t.create_time desc ");
			Page<SignedDto> response = signedService.getPageDtoModel(entity, PageUtil.begin(begin, row), row);
			List<SignedPageRes> signedListRes = new ArrayList<SignedPageRes>();
			List<SignedDto> sigendList = response.getRows();
			for(SignedDto dto : sigendList) {
				SignedPageRes res = new SignedPageRes();
				res.setSignedId(dto.getId());
				res.setCustomerName(dto.getCustomerName());
				res.setCustomerPhone(dto.getCustomerPhone());
				res.setSignedHouses(dto.getCombinedName());
				res.setSignedDate(dto.getCheckDate() == null?"":sdf.format(dto.getCheckDate()));
				res.setAuditStatus(AuditStatusEnum.getByNo(dto.getAuditStatus()).getDes());
				res.setUserName(dto.getUserName());

				res.setRecordBusiness("签约");
				if(AuditStatusEnum.REJECT.getNo().equals(dto.getAuditStatus())){
					res.setRecordBusiness("签约驳回");
				}else if(AuditStatusEnum.SUCCESS.getNo().equals(dto.getAuditStatus())){
					String businessStatus = dto.getBusinessStatus();
					String businessSecStatus = dto.getBusinessSecStatus();
					if(StringUtils.isNotBlank(businessSecStatus)){
						if(SignedBusinessStatusEnum.CHECKWARDS.getNo().equals(businessSecStatus)){
							res.setRecordBusiness("签约退房");
						}else {
							res.setRecordBusiness("签约");
						}
					}else{
						if(SignedBusinessStatusEnum.CHECKWARDS.getNo().equals(businessStatus)){
							res.setRecordBusiness("签约退房");
						}else {
							res.setRecordBusiness("签约");
						}
					}
				}
				signedListRes.add(res);
			}
			resDto.setSignedList(signedListRes);
			resDto.setPageNumber(response.getPageNumber());
			resDto.setPageSize(response.getPageSize());
			resDto.setTotalPage(response.getTotalPages());
			resDto.setTotalCount(response.getTotal());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			resDto.setErrorMsg("认购信息查询失败");
			resDto.setErrorCode("9999");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			logger.error("签约信息分页查询错误：{}",e);
		}
		return resDto;
	}

	/**
	 * 查询认购分页接口
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetSubscribePageResDto getSubscribePage(GetSubscribePageReqDto reqDto) {
		GetSubscribePageResDto resDto = new GetSubscribePageResDto();
		try {
			Integer begin = reqDto.getPageNumber();
			Integer row = reqDto.getPageSize();
			if (begin == null || row == null) {
				resDto.setErrorMsg("分页字段不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			String userId = reqDto.getUserId();
			if (StringUtils.isEmpty(userId)) {
				resDto.setErrorMsg("经纪人ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long merchantId = reqDto.getMerchantId();
			if (merchantId == null) {
				resDto.setErrorMsg("商户ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long projectId = reqDto.getProjectId();
			if (projectId == null) {
				resDto.setErrorMsg("项目ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			SubscribeDto entity = new SubscribeDto();
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService
						.dataPermissionCondition(Long.parseLong(reqDto.getUserId()), "menu_0005_0005", null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				entity.setDataPermission(dataPermissionArr[1]);
			}
			entity.setSql(reqDto.getQueryConditions());
			entity.setMerchantId(merchantId);
			entity.setProjectId(projectId);
			entity.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			entity.setM_businessStatus(" and t.business_status in (1,4)");
			entity.setIscustomerSub("1");
			entity.setOrders(" t.create_time desc ");
			Page<SubscribeDto> response = subscribeService.getSubscribeDtoList(entity, PageUtil.begin(begin, row), row);
			List<SubscribePageRes> subscribeListRes = new ArrayList<SubscribePageRes>();
			List<SubscribeDto> subList = response.getRows();
			for(SubscribeDto dto : subList) {
				SubscribePageRes res = new SubscribePageRes();
				res.setSubscribeId(dto.getId());
				res.setCustomerName(dto.getCustomerName());
				res.setCustomerPhone(dto.getCustomerPhone());
				res.setSubscribeDate(dto.getCheckDate() == null?"":sdf.format(dto.getCheckDate()));
				res.setSubscribeHouses(dto.getCombinedName());
				res.setAuditStatus(AuditStatusEnum.getByNo(dto.getAuditStatus()).getDes());
				res.setUserName(dto.getUserName());
				res.setRecordBusiness("认购");
				if(AuditStatusEnum.REJECT.getNo().equals(dto.getAuditStatus())){
					res.setRecordBusiness("认购驳回");
				}else if(AuditStatusEnum.SUCCESS.getNo().equals(dto.getAuditStatus())){
					String businessStatus = dto.getBusinessStatus();
					String businessSecStatus = dto.getBusinessSecStatus();
					if(StringUtils.isNotBlank(businessSecStatus)){
						if(SubscribeBusinessStatusEnum.REFUNDSUBSCRIPTION.getNo().equals(businessSecStatus)){
							res.setRecordBusiness("认购退房");
						}else {
							res.setRecordBusiness("认购");
						}
					}else{
						if(SubscribeBusinessStatusEnum.REFUNDSUBSCRIPTION.getNo().equals(businessStatus)){
							res.setRecordBusiness("认购退房");
						}else {
							res.setRecordBusiness("认购");
						}
					}
				}
				subscribeListRes.add(res);
			}
			resDto.setSubscribeList(subscribeListRes);
			resDto.setPageNumber(response.getPageNumber());
			resDto.setPageSize(response.getPageSize());
			resDto.setTotalPage(response.getTotalPages());
			resDto.setTotalCount(response.getTotal());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			resDto.setErrorMsg("认购信息查询失败");
			resDto.setErrorCode("9999");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			logger.error("认购信息分页查询错误：{}",e);
		}
		return resDto;
	}

	/**
	 * 修改首次接触方式app
	 * @param reqDto
	 * @return
	 */
	@Override
	public AddContactWayResDto addContactWay(AddContactWayReqDto reqDto) {
		AddContactWayResDto resDto = new AddContactWayResDto();
		if(reqDto.getCustomerId() == null) {
			resDto.setErrorMsg("客户ID不能为空");
			resDto.setErrorCode("0000");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		if(reqDto.getProjectId() == null) {
			resDto.setErrorMsg("项目ID不能为空");
			resDto.setErrorCode("0000");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		CustomerDto customerDto = new CustomerDto();
		customerDto.setFtContactWay(reqDto.getFtContactWay());
		customerDto.setFtContactTime(reqDto.getFtContactTime());
		customerDto.setFtContactContent(reqDto.getFtContactContent());
		String ftContactWay1 = reqDto.getFtContactWay1();
		if(StringUtils.isBlank(ftContactWay1)
				&& StringUtils.isNotBlank(reqDto.getFtContactContent1())) {
			ftContactWay1 = "电转访";
		}
		customerDto.setFtContactWay1(ftContactWay1);
		customerDto.setFtContactTime1(reqDto.getFtContactTime1());
		customerDto.setFtContactContent1(reqDto.getFtContactContent1());
		customerDto.setId(reqDto.getCustomerId());
		customerDto.setProjectId(reqDto.getProjectId());
		resDto = addCustomerManage.addContactWay(customerDto);
		return resDto;
	}

	/**
	 * 获取首次接触方式
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetContactWayResDto getContactWay(GetContactWayReqDto reqDto) {
		GetContactWayResDto resDto = new GetContactWayResDto();
		if(reqDto.getCustomerId() == null) {
			resDto.setErrorMsg("客户ID不能为空");
			resDto.setErrorCode("0000");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}

		if(reqDto.getProjectId() == null) {
			resDto.setErrorMsg("项目ID不能为空");
			resDto.setErrorCode("0000");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		CustomerDto customerDto = new CustomerDto();
		customerDto.setId(reqDto.getCustomerId());
		customerDto.setProjectId(reqDto.getProjectId());
		resDto = addCustomerManage.getContactWay(customerDto);
		return resDto;
	}

	@Override
	public String getRedirect(Long merchantId, String code) {
		ResourcesConfigDto config = new ResourcesConfigDto();
		config.setMerchantId(merchantId);
		config.setResourcesCode(code);
        List<ResourcesConfig> list = resourcesConfigMapper.selectListByDto(config);
		if(list.size()>0){
		    return list.get(0).getUrl();
        }
		return null;
	}
}
